2012-12-09 61 views
2

我在Jinja模板中編寫for循環時遇到困難,該模板對包含水果名稱的變量進行迭代,並且在主體中是該變量提供的變量的特性。對於Jinja2中的循環及其相關變量

因此,可以說,我們有我有困難以下變量

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

在for循環,遍歷該水果變量,然後在體內只調用特定的水果正在迭代變量創建。因此,在第一次迭代中,當值爲蘋果時,身體必須使用變量apple_color和apple_weight,並且類似地,第二次迭代香蕉體內的變量是banana_color和banana_weight。

這是否需要使用其他名稱列表?

回答

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 %}