hackohackob
hackohackob

Reputation: 66

How to populate up variables from included twig template

I want to be able to populate up variables from included twig templates, just like when you're extending another template. Here's an example:

I have base.twig as follows:

{# base.twig #}
<html>
    <head></head>
    <body class="body {{class_from_index}}">
        <nav>...</nav>
        {% block content %}
        {% endblock %}
        <footer>...</footer>
    </body>
</html>

and index.twig as follows:

{# index.twig #}
{% extends "base.twig" %}

{% set class_from_index = 'index' }

{% block content %}
    <div>My actual content</div>
{% endblock %}

doing like this, the variable class_from_index is populated to base.twig, when I'm rendering index.twig. However if i have gallery.twig like this:

{# gallery.twig #}
{% set class_from_index = 'gallery' %}
<div>
    A gallery
</div>

and adding {% include gallery.twig %} in index.twig, the variable class_from_index is not populated up to index.twig or base.twig. I know that if gallery.twig extends index.twig and index.twig extends base.twig, this will work, but this is not the case.

Is there a way to achieve what I'm trying to explain? Thank you :)

Upvotes: 0

Views: 580

Answers (1)

Alain
Alain

Reputation: 36954

The problem

If main.twig contains:

{% include "gallery.twig" %}

The compiled result will be:

protected function doDisplay(array $context, array $blocks = array())
{
    // line 1
    $this->loadTemplate("gallery.twig", "main.twig", 1)->display($context);
}

And if gallery.twig contains:

{% set var = 42 %}

The result is:

protected function doDisplay(array $context, array $blocks = array())
{
    // line 1
    $context["var"] = 42;
}

As you can see, the context is not given as a reference, so your variable can't be populated.

The PHP equivalent

The reason is quite obvious. It looks very exotic to use variables from a lower scope to a upper one. That's like if you were doing in PHP:

<?php

function gallery() {
  $var = 42;
}
gallery();

echo $var;

There must be a better solution to your problem... by designing your templates architecture another way. The question itself is not relevant, that's totally out of good practices.

Upvotes: 1

Related Questions