How can you add an item to an array within an include
tag when the array is defined in the main file?
Please note this question is distinctly different from other array questions in Twig because I'm trying to modify the value from within an included template in the main file.
For example:
main.twig
{% set includes = ["test1"] %}
{% include "test.twig" %}
{{includes|json_encode}} {# "How do I make this `includes` contain the "test2" array item?" #}
test.twig
{% set includes = includes|merge(["test2"]) %}
{{includes|json_encode}}
Currently the output from main.twig
gives me only the initial test1
item, and not the combination of the two which test.twig
is trying to modify.
I may have to utilize an added function. The goal here is basically to allow include
d templates the ability to add other CSS, JS, etc, in HTML files without having to modify the parent templates.
Here is a Twig Fiddle for you to play with which shows the output.
See Question&Answers more detail:osPlease note for other people looking for an answer to this question, what I was attempting to accomplish is possible utilizing a Twig extension with a function that adds items to the array, and a second function to access it. Please view my answer below, that is not marked as correct, to see a way to potentially do this. My question, as stated, is impossible, as shown by DarkBee.