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
Thanks for reading!
To find more programming tutorials, please visit: CodeBilby.com
Top comments (0)