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.
A shorter way to do this is:
{% set isOwner = user.isEqualTo(app.user|default(null)) %}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With