是否有更精简的方式在 Twig 模板中编写多行代码? [英] Is there a leaner way to write multiline code in Twig templates?

查看:17
本文介绍了是否有更精简的方式在 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.

更新:

虽然 DarkBee 的答案是缩短语法的方法,但要小心将 null 传递给可能需要特定类的对象的方法.我们最终使用的代码的最终版本并不比原始问题好多少,但至少少了一行:

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.

此外,如果您担心额外的空格会渗入 HTML(由于缩进),避免这种情况的最佳方法是将整段代码包装在 {% spaceless %} 中...{% endspaceless %} 标签.

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.

推荐答案

更短的方法是:

{% set isOwner = user.isEqualTo(app.user|default(null)) %}

这篇关于是否有更精简的方式在 Twig 模板中编写多行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆