在过去的几个小时中,我一直在尝试解决此问题,但距离解决方案还差得很远。我正在尝试返回D8段落模板内部的链接目标属性的字符串值:
当我使用计算机名称(field_link_cta)在字段上进行var转储时,请执行以下操作
{{ dump(content.field_link_cta['#items'].getValue()) }}
我得到了返回值:
我可以遍历变量以返回标题,但是由于某种原因无法访问链接属性?
{{ content.field_link_cta[0]['#title'] }}
-工作,返回值。
{{ content.field_link_cta[0]['#options']['#attributes']['#target'] }}
-不起作用,不返回任何值。
我在这里想念什么?鉴于我已经遍历了变量转储中列出的变量,是否不应该像标题一样返回'target'属性字符串?在这里是否有更好的方法来检查此变量的上下文?
任何指针将不胜感激。
感谢您的帮助!
标记。
答案 0 :(得分:2)
有两种选择:
选项1(更好):
{{ content.field_link_cta.0['#options']['attributes']['target'] }}
选项2:
{{ content.field_link_cta['#items'].getValue().0['options']['attributes']['target']) }}
说明:
您做了{{ dump(content.field_link_cta['#items'].getValue()) }}
,并且可以看到options属性和目标数组键没有#
。但是,除了转储以外,您从未使用过此选项(选项2)。
最好进行{{ dump(content.field_link_cta[0]) }}
,您会看到不同的转储,例如:
array (size=4)
'#type' => string 'link' (length=4)
'#title' => string 'link/text' (length=9)
'#options' =>
array (size=1)
'attributes' =>
array (size=3)
'target' => string '_blank' (length=6)
'rel' => string 'rel' (length=3)
'class' =>
array (size=1)
...
很显然,标题数组键具有#
,这就是{{ content.field_link_cta[0]['#title'] }}
起作用的原因。
属性和目标数组键没有#
,这就是{{ content.field_link_cta[0]['#options']['#attributes']['#target'] }}
不起作用的原因,正确的代码将是“选项1”下显示的代码。