[Twig] How to define variables / arrays and display of variables

I wrote an article about Smarty before, but another popular PHP template engine is Twig.
Since I’m using Symfony in my project, I’ve summarized here what I often look for in “variables”.

公式:set – Documentation – Twig

How to define variables in Twig

Use set to define variables within a Twig template.

Basic

{% set foo = 'bar' %}

Variable display

{# displays bar #}
{{ foo }}

The basics of defining and using variables are very simple.

Define multiple at once

{% set foo, bar = 'test', 'text' %}

{# display testtext #}
{{ foo }}{{ bar}}

 

How to define an array in Twig

You can also use set to define an array.

Basic

{% set foo = [10, 20] %}

{# display 10 #}
{{ foo.0 }}
{{ foo[0] }}

 

Name the Key and define the array

{# keys as string #}
{% set bar = {'a': 'test','b': 'text'} %}

{# display text #}
{{ bar.b }}

{# keys as names#}
{% set bar = {a: 'test',b: 'text'} %}

 

Define a combination of variables

You can also use variables for values and keys when defining variables with set.

{# 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 above example, you can also use expressions for variables and KEYs. It is convenient because you can attach variables to each other.

Sample how to use Set

This is a sample of a case that is often used in practice.

Combine variables to variables (strings and variables, etc.)

{% set foo = 'a' %}
{% set bar = 'b' %}
{% set test = foo ~ bar %}

{# display ab #}
{{ test }}


{% set baz = 'foo' ~ 'bar' %}

{# display foobar #}
{{ baz }}

 

Set the default value when the variable is false

{% set test = foo ?? 'default' %}

{# display default if foo is false #}
{{ test }}

 

Add (merge) an array to another array

It is familiar in PHP etc., but it is also possible on the Twig template side.

{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}

{# values now contains [1, 2, 'apple', 'orange'] #}

 

Define multiple lines such as html tags

{% set foo %}
    <div>
        test
    </div>
{% endset %}

 
The above is useful when you want to define multiple lines at once.

I would like to add more if I find a way to use it that I find useful through my work.