26

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

thegrunt
  • 1,054
  • 1
  • 11
  • 22
john Smith
  • 17,409
  • 11
  • 76
  • 117

1 Answers1

48

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])  %}
empiric
  • 7,825
  • 7
  • 37
  • 48
Markus Kottländer
  • 8,228
  • 4
  • 37
  • 61
  • this throws an exception : A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "[" – john Smith Dec 30 '13 at 14:23
  • 2
    yeah set is very ninja. you can also assign an array of objects to a variable with set and then loop through them. {% set cameras = { "family1": firstArray, "family2": secondArray }%} {% for identifier, item in cameras %} – thegrunt Feb 04 '14 at 22:33