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.

0

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

This won't work {% set itemClasses = 'item ' ~ loop.first ? 'active' %}, but this will do {% set itemClasses = 'item ' ~ (loop.first ? 'active') %}
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 %}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.