Search code examples
phptwigbolt-cms

How add elements in a multdimensional array on Twig?


I have this array called theme in a Twig template:

array:4 [▼
  "foo" => "bar"
  "headerimage" => array:6 [▶]
  "templatefields" => array:1 [▶]
  "assets" => array:3 [▼
    "css" => array:1 [▶]
    "js" => array:1 [▶]
    "libs" => array:2 [▼
      0 => "jquery"
      1 => "bootstrap"
    ]
  ]
]

I wanna add more elements in theme.assets.libs . I try with:

{% set theme.assets.libs = theme.assets.libs|merge(['otherlibrary', 'anotherlibrary']) %}

But I have the next error.

Unexpected token "punctuation" of value "." ("end of statement block" expected) in "index.twig" at line 7.


Solution

  • Twig doesn't allow doing this directly. You can instead, however, do this by continuing the pattern of array merges you're already doing:

    {% set theme = theme|merge({assets: theme.assets|merge({ libs: theme.assets.libs|merge(['otherlibrary', 'anotherlibrary']) }) }) %}