How would you append more data to the same variable in Twig? For example, this is what I'm trying to do in Twig:
var data = "foo";
data += 'bar';
I have figured out that ~
appends strings together in Twig. When I try {% set data ~ 'foo' %}
I get an error in Twig.
Use “~” to concatenate variables and strings {{ "Hello " ~ name ~ "!" }}
#Using the ~ (Tilde) Operator The tilde character concatenates all operands (strings and/or variables) into a single string. For example: {{ foo ~ ' ' ~ bar ~ '!'
In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .
The ~
operator does not perform assignment, which is the likely cause of the error.
Instead, you need to assign the appended string back to the variable:
{% set data = data ~ 'foo' %}
See also: How to combine two string in twig?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With