Chris Francart Chris Francart - 4 months ago 15
Twig Question

Passing Twig variables from array into an include

I have an array I'm iterating over to pull in different types of components into my page:

array(
'content'=> array(
'componentA'=>array(
'val'=>'1',
'title'=>'sample title'
),
'componentB'
)
)


I'm attempting to pass variables through from the array to the included template, but I'm not sure how to turn that string produced by the join into something that the include can understand as an array of variables. When I exclude the "with" from the first @components include, it prints out all the default values I've set in the iterable components like I would expect, but still gives me a white screen when I keep the with attribute in. When I display var itself, it returns this string:
(Note, I've also tried putting quotes around the {{k}} to no avail)

{ val:'1',title:'sample title' }


How can I pass the variables from my array to my component?

{% for key,item in content %}
{% if item is iterable %}

{% set var = [] %}
{% for k,v in item %}
{% set temp %}{% if loop.first %} { {% endif %}{{ k }}:'{{ v }}'{% if loop.last %} } {% endif %}{% endset %}
{% set var = var|merge([ temp ]) %}
{% endfor %}
{% set var = var|join(',') %}

{{ include ("@components/" ~ key ~ ".tmpl",var) }}
{% else %}
{{ include ("@components/" ~ item ~ ".tmpl") }}
{% endif %}
{% endfor %}

Answer

Your include statements are incorrect. You are using {{ include ... }}, which should be {% include ... %}.

The following snippet should work, if you only want to provide the data from the array (and not the loop data):

{% for key,item in content %}
    {% if item is iterable %}
        {% include ("@components/" ~ key ~ ".tmpl") with item %}
    {% else %}
        {% include ("@components/" ~ item ~ ".tmpl") %}
    {% endif %}
{% endfor %}

You can then use {{ val }} and {{ title }} within your component template.

If you want to include the loop data, you can use:

{% for key,item in content %}
    {% if item is iterable %}
        {% include ("@components/" ~ key ~ ".tmpl") with {item: item, loop: loop} %}
    {% else %}
        {% include ("@components/" ~ item ~ ".tmpl") %}
    {% endif %}
{% endfor %}

You can then use {{ item.val }}, {{ item.title }} and {{ loop.index }} in your component template.

Comments