Evans Evans - 4 months ago 12
Twig Question

Pass include path from variable with Twig?

I need to include child-1.twig and child-2.twig in component.twig, and include component.twig in page.twig.

In my page.twig:

{% set items = [
'{% include "child-1.twig" %}',
'{% include "child-2.twig" %}'
] %}

{% include "component.twig" with items %}


In component.twig:

<div class="component">
{% for item in items %}
{{ item }}
{% endfor %}
</div>


The complexity comes from the fact that I cant modify component.twig, only page.twig. My code above would work if
{% include "child-1.twig" %}
and
{% include "child-2.twig" %}
were rendered but instead they are printed onto the page as a string of text.

Can I do something similar to my approach but make the child include actually run?

Answer

Can I suggest you add an empty block in that file (component.twig)

{% block includes %}{% endblock %}

Then you will be able to do this:

{% embed "component.twig" with items %}
    {% block includes %}
        {% include "child-1.twig" %}
        {% include "child-2.twig" %}
    {% endblock %}
{% endembed %}
Comments