Is there a leaner way to write multiline code in T

2019-06-17 18:08发布

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.

标签: twig
2条回答
Ridiculous、
2楼-- · 2019-06-17 19:03

A shorter way to do this is:

{% set isOwner = user.isEqualTo(app.user|default(null)) %}
查看更多
成全新的幸福
3楼-- · 2019-06-17 19:06

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

查看更多
登录 后发表回答