在 twig 三元中定义

use*_*531 5 php twig

请考虑{{ item.nw is defined and item.nw ? ' target="_blank"' }}以下脚本。有没有更简洁的方法来做到这一点?

我认为{{ item.nw ?? ' target="_blank"' }}可能有效,但item.nw如果item.nw不是falsetarget="_blank"'如果item.nw是,它会返回false(参考https://twig.symfony.com/doc/2.x/templates.html#test-operator

{% macro menu(menu,active) %}
{# menu is an associated array of containing:
name.  required
path or id: One of the two are required.  If both, URL will use path
path.  optional and defaults to javascript:void(0)
id.  optional and defaults to not adding an id to the item.
nw.  optional and defalts to false.  This is a flag for a new window.
class.  optional and defaults to not adding an class to the item.
#}
{% for item in menu %}
{% set path = item.path is defined?item.path:"javascript:void(0)" %}
{% set id = item.id is defined?item.id:null %}
{% set class = item.class is defined?item.class:"" %}
{% if (path == active or id == active) %}
{% set class = class~' active ' %}
{% endif%}
{% if loop.first %}
{% set class = class~' first ' %}
{% elseif loop.last %}
{% set class = class~' last ' %}
{% endif %}
<li class="{{ class|trim }}">
    <a href="{{ path }}"{{ item.nw is defined and item.nw ? ' target="_blank"' }}{{ id?"id=#{id}" }}>{{item.name}}</a>
</li>
{% endfor %}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

小智 6

如果“已定义且不为空”,则空合并只会返回左侧的值。请记住 false 也是一个值。

{{ item.nw ?? ' target="_blank"' }}
Run Code Online (Sandbox Code Playgroud)

当“严格模式”打开时,您应该检查 Twig 模板中使用的每个变量。它可能很冗长,但这比破坏模板要好。

如果使用默认过滤器,还有其他方法可以检查变量。https://twig.symfony.com/doc/2.x/filters/default.html

{{ item.nw|default() is not false ? ' target="_blank"' }}

{{ item.nw|default() == 'some_value' ? ' target="_blank"' }}
Run Code Online (Sandbox Code Playgroud)