简体   繁体   中英

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 ?

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

The _context variable holds all variables in the current context. Instead of using the attribute function , you can access values of the _context array with the regular bracket notation as well:

{% for fruit in fruits %}
    {{ _context['help_' ~ fruit] }}
{% endfor %}

I would personally do it this way as it's more concise and in my opinion clearer.

You might want to check for undefined variables when accessing values of the _context array. I have written about it in my answer to this question: Symfony2 - How to access dynamic variable names in twig .


You also asked whether something like this is possible:

{% set attribute(context, 'help' ~ fruit, "value") %}

That's not possible. If you want to set variables with dynamic names, you need to create a Twig extension. Take a look at my answer to this question: How to set a variable name with dynamic variables?

But, like @user9189147 mentioned, it would be easier and in my opinion clearer if you instead created a new array to hold the help values. Then you wouldn't need to create an extension.

$data['fruits'] = ['apple', 'banana', 'orange'];
$data['help']   = [];
$data['help']['apple']  = 'This is help apple';
$data['help']['banana'] = 'This is help for banana';
$data['help']['orange'] = 'This is help for orange';
{% for fruit in fruits %}
    {{ help[fruit] }}
{% endfor %}

Then you can set new values to the help values in Twig using the merge filter , like this (though I don't know why you would want to do it in Twig):

{# Set single value #}
{% set help = help|merge({
    banana: 'New help for banana',
}) %}

{# Or multiple values #}
{% set help = help|merge({
    apple:  'An apple a day keeps the doctor away',
    orange: 'Orange is the new black',
}) %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM