How can I set a variable's name with the value of another value in Twig? I would think that It would go something like this:
{% set queCount = loop.index %}
{% for row2 in answer+queCount %}
But this does not work. Also making a string from that will break the loop (because it does not search for a string).
I know how to do this in PHP so for clarification, this is what I would like to achieve:
$count = 1;
$args["answer$count"]
which returns
$args["answer1"]
But this time, not with strings but the operant answer.
Thanks in advance!
Mats de Waard.
You can use the _context
variable
{% set queCount = loop.index %}
{% for row2 in _context['answer' ~ queCount] %}
Here is the doc about _context and global variables
In these cases you must use the attribute()
function:
{% for row2 in attribute(args, 'answer' ~ queCount) %}
...
{% endfor %}
More information: http://twig.sensiolabs.org/doc/functions/attribute.html
If the environment option strict_variables
is set to true
(the default value is false
, see docs ), @pbenard's answer will cause a fatal error if a variable doesn't exist. For example, if answer3
doesn't exist, you get something like this:
Fatal error: Uncaught Twig_Error_Runtime: Key "answer3" for array with keys "answer1, answer2, row, queCount, _parent, _seq, loop, _key" does not exist in "index" at line 9.
When the option is set to false
, unexisting variables are silently defaulted to null
. (That's why you don't get the error.)
You can avoid the problem by providing a default value with the default
filter:
{% set queCount = loop.index %}
{% for row2 in _context['answer' ~ queCount]|default(null) %}
You can also omit the value and even the parentheses. The variable will then default to an empty string. The end result is the same because both null
and an empty string are falsey values, so they are skipped in the for
loop. Ie these two are equal and valid:
{% for row2 in _context['answer' ~ queCount]|default() %}
{% for row2 in _context['answer' ~ queCount]|default %}
I'd argue that generally it's better to set strict_variables
to true
to avoid accidental errors caused by eg typos in variable names. Even if it's set to false
, using the default
filter in cases like this is a good thing to do so that you can later set the option to true
without worrying about breaking existing code.
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.