gremo
gremo

Reputation: 48909

Does Twig allow assignments in conditions and how?

As per title, does Twig allow assignments in conditional and how? I know that not all people like these assignments but sometimes they can be very helpful.

This:

{% if (name = attribute(mappings, property)) is defined %}
    {% else %}
    {% set attrs = attrs|merge(['%s="%s"'|format(name, value)]) %}
{% endif %}

...is not working and gives me and error:

An opened parenthesis is not properly closed. Unexpected token "operator" of value "=" ("punctuation" expected with value ")") in ::tooltips.html.twig at line 29.

Upvotes: 0

Views: 1702

Answers (1)

Peter Bailey
Peter Bailey

Reputation: 105888

Your twig error is because of this line

{% if (name = attribute(mappings, property)) is defined %}

Twig doesn't like assignment-in-condition expressions, and personally neither do I, it's just a lazy shortcut and the potential issues isn't worth saving a few keystrokes.

But I have to now admit that I'm confused by what this is supposed to do. You're attempting to capture the result of attribute(mappings, property) into name but if that fails, only then do you do something using name, but by then name won't have a value unless it's been defined elsewhere in the template.

Upvotes: 1

Related Questions