Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a leaner way to write multiline code in Twig templates?

Tags:

twig

If I have a block of code like this:

{% if app.user is defined %}
    {% set isOwner = user.isEqualTo(app.user) %}
{% else %}
    {% set isOwner = false %}
{% endif %}

Is it possible to write it without wrapping every line in tags, like this?

{% if app.user is defined
    set isOwner = user.isEqualTo(app.user)
else
    set isOwner = false
endif %}

The above code obviously doesn't work, because there are no line terminators. Adding a ; doesn't work either.

If there are a lot of lines, things get really complicated.

Update:

While DarkBee's answer is the way to shorten the syntax, be wary of passing null to a method that may be expecting an object of a particular class. The final version of the code we eventually went with is not much better than the original question, but at least it's one less line:

{% set isOwner = false %}
{% if app.user is not null %}
    {% set isOwner = user.isEqualTo(app.user) %}
{% endif %}

This way, the boolean flag is always set and the method never receives a null object.

Also, if you're worried about extra spaces creeping into your HTML (as a result of the indentation), the best way to avoid that is to wrap that whole piece of code in {% spaceless %}...{% endspaceless %} tags.

like image 468
aalaap Avatar asked Feb 23 '17 11:02

aalaap


2 Answers

A shorter way to do this is:

{% set isOwner = user.isEqualTo(app.user|default(null)) %}
like image 188
DarkBee Avatar answered Oct 30 '22 00:10

DarkBee


I think no, you can use a ternary operator like:

{% set isOwner = (app.user is defined  and user.isEqualTo(app.user)) ? true : false %}

Hope this help

More info here in the doc

like image 34
Matteo Avatar answered Oct 30 '22 00:10

Matteo