Yan's Blog

Yan's Blog

String Concatenation and Interpolation in Twig

String Concatenation and Interpolation in Twig

Subscribe to my newsletter and never miss my upcoming articles

Twig has two useful operations, ~ and #{}, for string concatenation and interpolation respectively.

String concatenation

We can use the operator ~ to convert all operands into strings and append one string to the end of another. For example, in PHP, we pass two variables to the template string.twig.

echo $twig->render('string.twig', array("numA" => "1", "numB" => "9"));

In the template file string.twig, we can use the operator ~ to concatenate the strings.

<P>{{ "Number A is: " ~ numA}}<br>
   {{ "Number B is: " ~ numB}}
</p>

The output will be:

Number A is: 1
Number B is: 9

String interpolation

Within a double-quoted string, we can use the interpolation operator #{} to evaluate a valid expression and the result is converted to a string for display. In the template file, we can do like this:

<P>
   {{ "A + B = #{numA + numB}"}}
</p>

The numbers numA and numB will be added together, and the output will be:

A + B = 10
#php#web-development
 
Share this