twig - building array in for loop

自作多情 提交于 2020-01-22 13:13:55

问题


is it possible to iteratively fill a twig array with values?

{% for question in questions %}
{% set multipleChoiceArray = [] %}
    {% for multipleChoice in question.multipleChoiceAnswers %}
        {% set multipleChoiceArray = multipleChoiceArray|merge( multipleChoice.answerText )  %}
    {% endfor %}
{% endfor %}

the problem is here multipleChoiceArray|merge(multipleChoice.answerText)

when i try to pass an array for example with key = loop.index like

{% set multipleChoiceArray = multipleChoiceArray|merge({"loop['index']":"multipleChoice['answerText']"})  %}

it works but the array contains the strings "["loop['index']":"multipleChoice['answerText']"]"

when i try to pass variables like :

{% set multipleChoiceArray = multipleChoiceArray|merge({loop.index:multipleChoice.answerText})  %}

exception is : A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "." ("punctuation" expected with value ":")

so i am not able to "push" a value "multipleChoice.answerText" into "multipleChoiceArray"

any hints how that is possible ? i just want to gather all possible answers and later check if answer is in that array and count sth up and display


回答1:


The argument of merge has to be an array or object to merge it with an existing one. So write it as an array with one element.

{% set multipleChoiceAnswerText = multipleChoice.answerText %}
{% set multipleChoiceArray = multipleChoiceArray|merge([multipleChoice.answerText])  %}


来源:https://stackoverflow.com/questions/20841206/twig-building-array-in-for-loop

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