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 nslt的可用模型,或者其他可以进行推理的现有模型
  • ¥15 arduino上连sim900a实现连接mqtt服务器
  • ¥15 vncviewer7.0安装后如何正确注册License许可证,激活使用
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并2
  • ¥66 关于人体营养与饮食规划的线性规划模型
  • ¥15 基于深度学习的快递面单识别系统
  • ¥15 Multisim仿真设计地铁到站提醒电路
  • ¥15 怎么用一个500W电源给5台60W的电脑供电
  • ¥15 请推荐一个轻量级规则引擎,配合流程引擎使用,规则引擎负责判断出符合规则的流程引擎模板id
  • ¥15 Excel表只有年月怎么计算年龄