【问题标题】:For Loop in Jinja2 with related variables带有相关变量的 Jinja2 中的 For 循环
【发布时间】:2012-11-27 01:35:07
【问题描述】:

我很难在 Jinja 模板中编写一个 for 循环,该循环遍历一个包含水果名称的变量,并且在正文中是该水果的特征,该特征也作为变量提供。

假设我们有以下变量

fruit=apple,banana,grapes
apple_color=red
apple_weight=1kg
banana_color=yellow
banana_weight=2kg
grapes_color=green
grapes_weight=3kg

我很难创建一个迭代水果变量的 for 循环,然后在正文中调用仅特定于被迭代水果的变量。因此,在第一次迭代中,当 value 为 apple 时,body 必须使用变量 apple_color 和 apple_weight,类似地,对于第二次迭代 banan,body 中的变量是banana_color 和banana_weight。

这需要使用列表来做其他事情吗?

【问题讨论】:

    标签: python for-loop jinja2


    【解决方案1】:

    在您的代码中:

    fruits = {'apple' : {'color', apple_color, 'weight' : apple_weight}, 'banana' : {'color' : banana_color, 'weight' : banana_weight}, 'grapes' : {'color' : grapes_color, 'weight' : grapes_weigh}} 
    
    or if you use your already defined variables like  : apple_color = 'red'
    
    fruit_names = ['apple', 'banana', 'grapes']
    fruits = {}
    for each in fruit_names :
        fruits[each] = {}
        fruits[each]['color'] = globals()['%s_%s' %(each, 'color')]
        fruits[each]['weight'] = globals()['%s_%s' %(each, 'weight')]
    

    在您的模板中:

    {% for each in fruits %}
        {{ fruits[each].color }}
        {{ fruits[each].weight }}
    {% endfor %}
    
    or :
    
    {% for key, value in fruits.items() %} 
        {{ key }}
        {{ value.color }} 
        {{ value.weight }} 
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2019-06-14
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多