FORSMILE
JA
Twig2021/01/20

[Twig] How to Define Variables and Arrays (using `set`) and Display Them

I've previously written about Smarty, but Twig is another frequently used PHP template engine.

Back to Blog

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

css
{% set foo = 'bar' %}
css
{# displays bar #}
{{ foo }}

Defining Multiple Variables at Once

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

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

HOW TO DEFINE ARRAYS IN TWIG

Basic

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

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

Defining Arrays with Named Keys

css
{# 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.

javascript
{# 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)

css
{% 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

css
{% 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.

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

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

Defining Multiline Content like HTML Tags

css
{% 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.

📦
Amazon で関連書籍・ツールを検索
PHP Twig template engine
Amazonで探す →(アソシエイトリンク)