du16178 2014-07-09 21:58
浏览 45
已采纳

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

I have the folowing long variable in Twig to read the src attribute of an image in RSS feed:

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

I want to make the code more cleaner and readable, so initially, I defined two variables to act as parameter of get_item_tags() and the other as a path for the array:

{% 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']' %}

What I want to get, but it generate error, is:

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

I don't use symfony and Twig version is 1.16.0

  • 写回答

1条回答 默认 最新

  • dsjojts9734 2014-07-10 15:29
    关注

    When you set a variable in twig and want to use it inside another function either in {{ }} or {% %} you do not need to use {{ }} again for the set variable.
    Furthermore, you cannot set a variable as index of another variable then concat them; so you need to change it to:

    {% 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'] }}" />
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?