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?
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With