Skip to content

Instantly share code, notes, and snippets.

@olets
Last active July 10, 2023 17:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olets/54c24b4843064aa80034e34d18d37d88 to your computer and use it in GitHub Desktop.
Save olets/54c24b4843064aa80034e34d18d37d88 to your computer and use it in GitHub Desktop.
Global variables in Twig
{% block a %}{{ x ?? 5-4 }}{% endblock %}
{% block b '2' %}
{% macro d() %}4{% endmacro %}
{% macro e() %}5{% endmacro %}
{% macro f(n) %}
{{ n * block('b', 'globals.twig') }}
{% endmacro %}
`use`ing is convenient if you have several variables in one file.
{% use 'globals.twig' %}
{{ block('a') }}
{{ block('b') }}
{{ 5 - block('a') }}
Individual blocks can be pulled in from individual templates.
{{ block('c','more-globals.twig') }}
{{ 1 - block('c','more-globals.twig') }}
For ease of resuse, assign these to local variables:
{% set a = block('a') %}
{% set b = block('b') %}
{% set c = block('c', 'more-globals.twig') %}
{{ a + b + c }}
But the most compact is to use macros, either under a name
{% import 'macros--globals.twig' as globals %}
{{ globals.d }}
or not
{% from 'macros.twig' import e %}
{{ e() }}
though you can't operate on those:
{{ e() + 1 }} is 2 not 6, {{ e() - 1 }} is 0 not 4.
And you can combine `block()` and `macro` to use global values in a macro:
{% import 'macros.twig' as macros %}
{{ macros.e(3) }}
{% block c %}3{% endblock %}
`use`ing is convenient if you have several variables in one file.
1
2
4
Individual blocks can be pulled in from individual templates.
3
-2
For ease of resuse, assign these to local variables:
6
But the most compact is to use macros, either under a name
4
or not
5
though you can't operate on those:
2 is 2 not 6, 0 is 0 not 4.
And you can combine `block()` and `macro` to use global values in a macro:
5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment