Twig 中是否有任何方法可以确定 method/parameter 是否存在而不用到处放置 ifs?

Is there any way in Twig to determine if a method/parameter exists without putting ifs everywhere?

同时使用Symfony2和Twig时,如果需要这样做:

<td>{{ myObject.method.parameter }}</td>

或者只是

<td>{{ myObject.parameter }}</td>

如果未设置 twig 文件试图访问的内容,则会抛出错误。 除了到处写这个之外,有没有更干净的方法来防止这种情况:

<td>{% if myObject.method.parameter is defined %}{{ myObject.method.parameter }}{% endif %}</td>

最近和Angular一起工作很愉快,因为它似乎并不在意。

纯 Twig 解决方案是使用 default 过滤器:

http://twig.sensiolabs.org/doc/filters/default.html

它看起来像这样,对我来说很好用:

{{ myObject.it.is.not.designed|default('it is not defined') }}  

默认文本可以是空字符串''

现在您必须为每个变量设置默认值。与 {% autoescape %} 不同,似乎无法为更大的代码区域定义过滤器。为了简单起见,我会创建一个宏:

{% macro safeEcho(value) %}
  {{ value | default('') }}
{% endmacro %}

别忘了导入:

{% import _self as helper %}

测试:

Test:{{ helper.safeEcho(echolabels.something.something_2) }}

如果我经常使用这个,我会考虑短名称,尽管我通常不使用缩写:h.se()

关于宏的更多信息:

http://twig.sensiolabs.org/doc/tags/macro.html

如果您从根本上需要这个,可能会覆盖 Twig 词法分析器:

http://twig.sensiolabs.org/doc/internals.html

我不太了解 Twig 作为 Symfony2 的一部分。可能是它的配置提供了另一个选项:

http://symfony.com/doc/current/reference/configuration/twig.html

最后看到这里这个问题之前有人问过,答案不一样。

How to check for null in Twig?

symfony, twig - default filter for all variables in template

也许 Twig 开发人员应该考虑提供 "general variable default" 选项:-)