How to combine and concatenate variables and strings [Twig]

This is an introduction of how to combine variables and strings on a Twig template.
Actually, I have introduced the operators that can be used in Twig, but when I actually use it, I will write it in a separate page so that I can leave it with a title that is easy to associate.

[Twig] Summary of available operators

Use “~” to concatenate variables and strings

{% set name = 'tester' %}
{{ "Hello " ~ name ~ "!" }}
// result
Hello tester!

 
The variable name is combined with the string.
It’s easy if you know what to use for the combiner!

Combine variables and strings using “#{expression}”

{{ "foo #{1 + 2} baz" }}
// result
foo 3 baz

 
It is used for calculations such as formulas, but of course variables can also be used.

{% set name = 'tester' %}
{{ "foo #{name} baz" }}
// result
foo tester baz

 
It’s like this. I feel that combining variables and strings is surprisingly common.
For your reference.


Leave a Reply 0

Your email address will not be published.

eleven − 8 =