sponge bob sponge bob - 4 years ago 128
PHP Question

Write a specifc key to parse object with Twig

I can't find the way to parse an array with a generate key with Twig :

My object post :

[blocks_content_0_title] => Title0
[blocks_content_1_title] => Title1
[blocks_content_2_title] => Title3


With Twig I can get value normally : post.blocks_content_0_title and it display Title0

But in my code I need to push specific key with variable for display value. And I can't parse with a classical twig for my object


My question is, how to insert a variable in key ?


Examples (and it doesn't work) :

{{ post.blocks_content_~myNumber~_title }}
{{ post['blocks_content_'~myNumber~'_title'] }}


Sorry for this horrible english ;)
Thanks for your help !

Answer Source

Try using attribute():

{{ attribute(post, 'blocks_content_' ~ myNumber ~ '_title') }}

http://twig.sensiolabs.org/doc/2.x/functions/attribute.html

Personally, I'd consider refactoring so I don't have to do this in a template.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download