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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀