是否有可能迭代填充一个twig数组与值?
{% for question in questions %} {% set multipleChoiceArray = [] %} {% for multipleChoice in question.multipleChoiceAnswers %} {% set multipleChoiceArray = multipleChoiceArray|merge( multipleChoice.answerText ) %} {% endfor %} {% endfor %}
这里的问题是multipleChoiceArray | merge(multipleChoice.answerText)
当我尝试传递一个数组,例如key = loop.index like
{% set multipleChoiceArray = multipleChoiceArray|merge({"loop['index']":"multipleChoice['answerText']"}) %}
它工作,但数组包含字符串“[”loop [‘index’]“:”multipleChoice [‘answerText’]“]”
当我尝试传递变量,如:
{% set multipleChoiceArray = multipleChoiceArray|merge({loop.index:multipleChoice.answerText}) %}
异常是:哈希键后面必须有一个冒号(:).意外令牌“标点符号”的值“”. (“标点符号”预期值为“:”)
所以我无法“推”一个值“multipleChoice.answerText”到“multipleChoiceArray”
合并的参数必须是一个数组或对象,以将其与现有数组或对象进行合并.所以把它写成一个包含一个元素的数组.
{% set multipleChoiceAnswerText = multipleChoice.answerText %} {% set multipleChoiceArray = multipleChoiceArray|merge([multipleChoice.answerText]) %}