17

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.

svict4
  • 432
  • 8
  • 24
Jon
  • 8,205
  • 25
  • 87
  • 146

3 Answers3

31

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?

Community
  • 1
  • 1
Andrew
  • 2,770
  • 1
  • 22
  • 29
  • This won't work `{% set itemClasses = 'item ' ~ loop.first ? 'active' %}`, but this will do `{% set itemClasses = 'item ' ~ (loop.first ? 'active') %}` – Vlad Moyseenko Mar 25 '23 at 20:33
0

Displaying dynamically in twig

{% for Resp in test.TestRespuestasA %}        
    {% set name = "preg_A_" ~ Resp.id %}
    {% set name_aux = "preg_A_comentario" ~ Resp.id %}
    <li>{{ form_row(attribute(form, name)) }}</li>
{% endfor %}
chopper
  • 6,649
  • 7
  • 36
  • 53
Rodolfo Velasco
  • 845
  • 2
  • 12
  • 27
0

You can also define a custom filter like Liquid's |append filter in your Twig instance which does the same thing.

$loader = new Twig_Loader_Filesystem('./path/to/views/dir');
$twig = new Twig_Environment($loader);

...
...

$twig->addFilter(new Twig_SimpleFilter('append', function($val, $append) {
    return $val . $append;
}));

Resulting in the following markup:

{% set pants = 'I\'m wearing stretchy pants!' %}
{% set part2 = ' and they\'re friggin\' comfy!' %}
{% set pants = pants|append(part2) %}

{{ pants }}

{# result: I'm wearing stretchy pants! and they're friggin' comfy! #}

IMHO I find the above sample more intuitive than the ~ combinator, especially when working on a shared codebase where people new to the syntax might get a bit mixed up.

bmcminn
  • 106
  • 1
  • 6