1

I'm trying to figure out how to load a template file and pass it as a variable to another template file while it is being included. In some sense I want to do something like this:

{% include 'component/footer', with 'component/nav' %}

I know I can't do that directly, but in the twig documentation there is an example showing this:

$template = $twig->load('some_template.twig');
$twig->display('template.twig', array('template' => $template));

Is it possible to do the same thing with Craft's twig support?

1 Answer 1

3

You can't do it exactly like that in Twig. But there're different approaches that'd do the same thing depending on exactly what you're trying to achieve.

For instance, you could parse the template into a variable, and then pass the variable to your include:

{% set nav %}
    {% include 'component/nav' %}
{% endset %}

{% include 'component/footer' with { nav: nav } %}

Or, you could just pass in the template name as a string, and parse it inside the component/footer template. In you base template:

{% include 'component/footer' with { navTemplateName: 'component/nav' } %}

Inside component/footer:

{% include navTemplateName %}

What approach suits your use case depends on whether or not the scope that component/nav is parsed in, matters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.