DEV Community

Yongyao Yan
Yongyao Yan

Posted on • Originally published at codebilby.com

String Concatenation and Interpolation in Twig

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"));
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

The output will be:

Number A is: 1
Number B is: 9
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

A + B = 10
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!
To find more programming tutorials, please visit: CodeBilby.com

Top comments (0)