phpsymfonytwigtwig-filter

Twig print available from string


How to print available form string in twig In my code php

$data['fruits'] = array('apple', 'banana', 'orange');
$data['help_apple'] = 'This is help apple';
$data['help_banana'] = 'This is help for banana';
$data['help_orange'] = 'This is help for orange';

In twig template

{% for fruit in fruits %}
{{ "help_" ~ fruit }}
{% endfor %}

The print screen is help_apple, help_banana, help_orange How to print correct data i need for help_ fruit key ?


Solution

  • You need to use the attribute function with _context. Tested on twigfiddle.com. Hope this helps.

    {% for fruit in fruits %}
        {# Here is how you do it #}
        {{ attribute(_context, 'help_'~ fruit) }}
    {% endfor %}