Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable data between blocks in twig

Tags:

twig

symfony

Twig:

{% set var = 'apple' %}

{% block A %}
    {{ var }} {# This prints apple #}
{% endblock %}

{% block B %}
    {% set var = 'banana' %}
    {{ var }} {# This prints banana #}
{% endblock %}

{% block C %}
    {{ var }} {# This prints apple, but I want it to print banana #}
{% endblock %}

Is there any way to get the changed value from block B in block C?

like image 751
Zuhayer Tahir Avatar asked Oct 17 '22 15:10

Zuhayer Tahir


1 Answers

You can hack it and set the value in your $_SESSION variable and access it in the required block:

{% set var = 'apple' %}

{% block A %}
    {{ var }} {# This prints apple #}
{% endblock %}

{% block B %}
    {% set var = 'banana' %}
    {{ var }} {# This prints banana #}
    {{ app.session.set('var', var) }}
{% endblock %}

{% block C  %}
    {{ var }} {# This prints apple #}
    {% set var = app.session.get('var') %}
    {{ var }} {# This prints banana #}
{% endblock %}

Here is the twigfiddle to show you.

Or In the comment section you mentioned that you want to access a variable in {% block javascripts %} which has been set in {% block body %}. You can hack it and move your js code in your body block. But I prefer to keep my js code in one place.

{% set var = 'apple' %}

{% block A %}
    {{ var }} {# This prints apple #}
{% endblock %}

{% set var = 'banana' %}
{% block B %}
    {{ var }} {# This prints banana #}
`<script>{{ var }}</script>` {# Bring your js code in the required block#}
{% endblock %}
like image 154
Zuhayer Avatar answered Oct 21 '22 07:10

Zuhayer