在小树枝模板中设置变量,然后与另一个变量一起使用


Set variable in twig template then using it with another variable

我在Twig中有以下长变量来读取RSS提要中图像的src属性:

<img src="{{item.get_item_tags("http://www.w3.org/2005/Atom","link")[0]['child']['http://search.yahoo.com/mrss/']['content'][0]['child']['http://search.yahoo.com/mrss/']['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src']}}"/>

我想让代码更清晰易读,所以最初,我定义了两个变量作为get_item_tags()的参数,另一个作为数组的路径:

{% set param1 = 'http://www.w3.org/2005/Atom' %}
{% set arrayPath = '[0]['child']['http://search.yahoo.com/mrss/']['content'][0]['child']['http://search.yahoo.com/mrss/']['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src']' %}

我想要得到的,但它会产生错误,是:

<img src="{{item.get_item_tags({{param1}}, "link"){{arrayPath}}}}" />

我不使用symfony和Twig版本是1.16.0

当您在twig中设置了一个变量,并希望在{{ }}{% %}中的另一个函数中使用它时,您不需要再次使用{{ }}来设置变量。
此外,您不能将一个变量设置为另一个变量的索引,然后将它们连接起来;所以你需要把它改成:

{% set param1 = 'http://www.w3.org/2005/Atom' %}
{% set output = item.get_item_tags(param1, "link") %}
{% set yk = 'http://search.yahoo.com/mrss/' %}
<img src="{{ output[0]['child'][(yk)]['content'][0]['child'][(yk)]['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src'] }}" />