Sorry per advance for my english :/

I am trying to construct an twig array in a .twig file like this :

{% set allergenesArray = [] %}
    {% for allergne in recipe.allergenes %}
      {% set allergenesArray = allergenesArray|merge({
      }) %}
    {% endfor %}
    {{ dump(allergenesArray) }}

The result of the dump is Dump of the array.

The code works fine but in fact, I should have 2 objects : I think the first one is erased but I really don't why...

If anyone has an idea...

Thanks per advance and good evening

2 Answers 2


Note: I have used the English singular allergen and plural allergens in my examples here—it’s just easier for me to proofread in my native language!

I believe what is happening is that your code is repeatedly merging an associative array on top of an associative array, overwriting the same allergen key.

That said,recipe.allergens is probably already an array—can you just use it as-is? It would be helpful to know what kind of field you're working with.

To rebuild the array, you would need append to allergensArray, like this:

{% set allergensArray = [] %}

{% for allergen in recipe.allergens %}
  {# Create a single-element array to merge: #}
  {% set allergensArray = allergensArray|merge([allergen]) %}
{% endfor %}

{{ dump(allergensArray) }}

The core issue (I think) is that the curly braces inside your merge() filter (merge({ allergen })) is creating an object like this…

  allergen: (Allergen model 1)

…which is then getting merged with another object like this, the second time around…

  allergen: (Allergen model 2)

…and squashing the allergen key from the first loop.

Aside: I don't recognize App\Enti… as a Craft namespace—is this indeed a Craft application?


Thank you very much for your response which is very clear :

Yes, the recipe.allergens is an array which contains alergene types with an id and a name properties.

-> In DB : Allergen(id, name).

I tried your solution but it doesn't work. I don't think it is the good way to do...

{% set allergensArray = [] %}
    {% for allergen in recipe.allergenes %}
      {% set singleElement = {'id' : allergen.id, 'name' : allergen.name} %}
      {% set allergensArray = allergensArray|merge({singleElement}) %}
    {% endfor %}
    {{ dump(allergensArray) }}

The result is : Result

I am googling for a solution but not found for the moment.

Thank you again

  • 2
    Inside your merge, you need to wrap the singleElement with square bracket instead curly bracket, so it would allergensArray|merge([singleElement])
    – aodihis
    Commented Aug 28, 2023 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.