Twig set a variable name with a variable [TWIG/PHP]

对着背影说爱祢 提交于 2020-01-04 02:38:22

问题


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.


回答1:


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




回答2:


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




回答3:


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. I.e. 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 e.g. 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.



来源:https://stackoverflow.com/questions/34879695/twig-set-a-variable-name-with-a-variable-twig-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!