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转义的",Twig会正确解析字符串。
内容的提问来源于stack exchange,提问作者bobcares
相关产品推荐
相关产品推荐

