DEV Community

Yongyao Yan
Yongyao Yan

Posted on • Originally published at codebilby.com

3 2

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay