Lughino
Lughino

Reputation: 4118

Set variable in loop

I'm trying to create a json object on twig, so I need to set a variable inside a loop. After many attempts I found this way, but it's fine when I only have two records, if I have any more you generate the problem:

{% set data = [] %}
{% for artist in artists %}
     {% if loop.first %}
         {%
         set data = {
               id        : artist.id,
               text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
             }
         %}
     {% else %}
         {%
          set data = [data,{
              id        : artist.id,
              text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
            }]
         %}
     {% endif %}
 {% endfor %}
 {% set data = {results: data} %}
 {{ data|json_encode|raw }}

What I want to achieve is:

{results: [{id: 1, text: "bla"},{id: 2, text: "blabla"},{id: 3, text: "blablabla"}]}

Instead I get:

{results:[[{id:1,text:"bla"},{id:2,text:"blabla"}],{id:3,text:"blablabla"}]}

Is there a way to build a json object inside twig without going crazy?

I've already tried this way .. but rewrites the object and saves in the variable only the last element:

{% set data = [] %}
{% for artist in artists %}
     {%
      set data = {
          id        : artist.id,
          text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
        }
     %}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}

Upvotes: 0

Views: 138

Answers (1)

mattexx
mattexx

Reputation: 6606

Use merge.

{% set data = [] %}
{% for artist in artists %}
     {%
      set data = data|merge ([{
          id        : artist.id,
          text      : artist.name|capitalize() ~' '~ artist.surname|capitalize()
        }])
     %}
{% endfor %}
{% set data = {results: data} %}
{{ data|json_encode|raw }}

Upvotes: 1

Related Questions