You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal中Twig模板判断target="_blank"报错问题求助

解决Drupal Twig中判断target="_blank"时报错的问题

你遇到的报错根源是直接访问未定义的数组键:当链接没有配置target属性时,item.url.getOption('attributes')['target']会因为attributes数组里不存在target键而抛出错误。另外原代码里的HTML转义引号"也不符合Twig的语法规范。

下面提供两种可靠的解决方法:

方法一:先检查属性是否存在

通过default过滤器确保attributes始终是数组,再用is defined判断target键是否存在,最后验证值:

{% set attributes = item.url.getOption('attributes')|default({}) %}
{% if attributes.target is defined and attributes.target == '_blank' %}
  <span class="site-menu__link--external">
    {% include directory ~ '/templates/images/icons/email.svg' %}
  </span>
{% endif %}

方法二:使用空安全操作符(Twig 3+可用)

利用Twig的?.空安全链式访问,避免因属性不存在而报错:

{% if item.url.getOption('attributes')?.target == '_blank' %}
  <span class="site-menu__link--external">
    {% include directory ~ '/templates/images/icons/email.svg' %}
  </span>
{% endif %}

注意:代码中直接使用单引号或双引号即可,无需用HTML转义的&quot;,Twig会正确解析字符串。

内容的提问来源于stack exchange,提问作者bobcares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:20:45