duanlinma5885 2017-12-09 19:37
浏览 30
已采纳

在树枝三元中定义

Consider {{ item.nw is defined and item.nw ? ' target="_blank"' }} in the below script. Is there a more concise way to do this?

I thought {{ item.nw ?? ' target="_blank"' }} might work but it returns item.nw if item.nw is not false and target="_blank"' if item.nw is false (reference 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 %}
  • 写回答

1条回答 默认 最新

  • 普通网友 2017-12-09 20:28
    关注

    Null coalesce will only return the value on the left if "it is defined and not null". Remember that false is a value also.

    {{ item.nw ?? ' target="_blank"' }}
    

    When "Strict Mode" is turned on you should check every variable you use in the Twig Template. It might be verbose, but it's better than having your template break.

    There are alternative ways to check variables if you use the default filter. 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"' }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。