为什么这不起作用:
{% set relations = [{'cat':'friends','foo':'bar1'},{'cat':'enemies','foo':bar2},....] %}
{% set friends = [{'firstName':'John', 'lastName':'Goodman'},....] %}
{% set enemies = [{'firstName':'Ron', 'lastName':'Badguy'},....] %}
{% for relCat in relations %}
{% set list = relCat.cat %}
{% for person in list %}
{{ person.firstName }}
{% endfor %}
{% endfor %}
我承认我对树枝很新,所以我真的搜索和搜索,但找不到我的问题的解决方案(我认为是微不足道的)....
我希望有人可以提供帮助 - 我失去了所有的头发,谢谢,Rudolph
答案 0 :(得分:1)
变量顺序很重要 首先:敌人和朋友:
{% set friends = [{'firstName':'John', 'lastName':'Goodman'}] %}
{% set enemies = [{'firstName':'Ron', 'lastName':'Badguy'}] %}
然后设置关系:再次friends
而不是'friends
',第一个是变量,第二个是字符串:
{% set relations = [{'cat':friends,'foo':'bar1'},{'cat':enemies,'foo':bar2}] %}
{% for relCat in relations %}
{% set list = relCat.cat %}
{% for person in list %}
{{ person.firstName }}
{% endfor %}
{% endfor %}
这应该有效
请参阅fiddle
答案 1 :(得分:1)
如果确实需要保留字符串,您也可以使用_context
变量:
{% set relations = [{'cat':'friends','foo':'bar1'},{'cat':'enemies','foo':bar2}] %}
{% set friends = [{'firstName':'John', 'lastName':'Goodman'}] %}
{% set enemies = [{'firstName':'Ron', 'lastName':'Badguy'}] %}
{% for relCat in relations %}
{% set list = _context[relCat.cat] %} {# <--- here #}
{% for person in list %}
{{ person.firstName }}
{% endfor %}
{% endfor %}
请参阅fiddle