Twig - Append string data to same variable

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.

0

3 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?

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 %}

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like