Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - Append string data to same variable

Tags:

twig

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.

like image 258
Jon Avatar asked Nov 20 '12 18:11

Jon


People also ask

How do I concatenate strings in twig?

Use “~” to concatenate variables and strings {{ "Hello " ~ name ~ "!" }}

What is tilde in twig?

#Using the ~ (Tilde) Operator The tilde character concatenates all operands (strings and/or variables) into a single string. For example: {{ foo ~ ' ' ~ bar ~ '!'

How do you use variables in twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .


1 Answers

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?

like image 86
Andrew Avatar answered Nov 16 '22 01:11

Andrew