Dynamically accessing an object property or array index with Twig
Published on 2022-06-20 • Modified on 2022-06-20
This snippet shows how to access an object property or array index with Twig dynamically. We can use the same attribute()
function for both cases.
{% set obj = {'foo': 'valFoo', 'bar': 'valBar'} %}
{% set array = ['foo', 'bar'] %}
{% set varForObj = 'foo' %}
{% set varForArray = 0 %}
<ul>
<li>obj.foo: <b>{{ attribute(obj, varForObj) }}</b></li>
<li>array.0: <b>{{ attribute(array, varForArray) }}</b></li>
</ul>
HTML demo of the snippet
- obj.foo: valFoo
- array.0: foo
More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉