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.


HTML demo of the snippet
  • obj.foo: valFoo
  • array.0: foo

{% 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>

 More on Stackoverflow   Read the doc  Random snippet