【问题标题】:Set variable in twig template then using it with another variable在树枝模板中设置变量,然后将其与另一个变量一起使用
【发布时间】:2014-07-09 21:58:50
【问题描述】:

我在 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

【问题讨论】:

    标签: php twig template-engine


    【解决方案1】:

    当您在 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'] }}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-11
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多