Evans Evans - 1 year ago 200
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 %}

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" %}
{% 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 Source

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 %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download