I've previously written about Smarty, but Twig is another frequently used PHP template engine.
Since I'm also using Symfony in my projects, I've compiled this summary of frequently searched information regarding 'variables'.
HOW TO DEFINE VARIABLES IN TWIG
To define variables within a Twig template, you use `set`.
Basic
{% set foo = 'bar' %}{# displays bar #}
{{ foo }}Defining Multiple Variables at Once
{% set foo, bar = 'test', 'text' %}
{# display testtext #}
{{ foo }}{{ bar}}HOW TO DEFINE ARRAYS IN TWIG
Basic
{% set foo = [10, 20] %}
{# display 10 #}
{{ foo.0 }}
{{ foo[0] }}Defining Arrays with Named Keys
{# keys as string #}
{% set bar = {'a': 'test','b': 'text'} %}
{# display text #}
{{ bar.b }}
{# keys as names#}
{% set bar = {a: 'test',b: 'text'} %}Defining Variables by Combining Others
When defining variables with `set`, you can also use other variables for values or keys.
{# set foo variable #}
{% set foo = 'a' %}
{# value as variable #}
{% set test = foo %}
{# display a #}
{{ test }}
{# keys as expressions #}
{% set bar = { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' } %}
{# display foo bar baz #}
{{ bar.a }}
{{ bar.2 }}
{{ bar.ab }}As you can see from the example above, it's also possible to use expressions for variables and keys. This is useful for concatenating variables, for example.
EXAMPLES OF SET USAGE
Concatenating Variables (e.g., string and variable)
{% set foo = 'a' %}
{% set bar = 'b' %}
{% set test = foo ~ bar %}
{# display ab #}
{{ test }}
{% set baz = 'foo' ~ 'bar' %}
{# display foobar #}
{{ baz }}Setting a Default Value if a Variable is False
{% set test = foo ?? 'default' %}
{# display default if foo is false #}
{{ test }}Adding an Array to Another (Merging)
This is a common operation in PHP and similar languages, and it's also possible within Twig templates.
{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}
{# values now contains [1, 2, 'apple', 'orange'] #}Defining Multiline Content like HTML Tags
{% set foo %}
<div>
test
</div>
{% endset %}I will continue to add more useful usage patterns as I encounter them during my work.
RECOMMENDED TWIG BOOKS
I haven't read any books exclusively dedicated to Twig, but I found one on Amazon Kindle.
📦