私の辞書は次のようになります(辞書内の辞書):
{'0': {
'chosen_unit': <Unit: Kg>,
'cost': Decimal('10.0000'),
'unit__name_abbrev': u'G',
'supplier__supplier': u"Steve's Meat Locker",
'price': Decimal('5.00'),
'supplier__address': u'No\r\naddress here',
'chosen_unit_amount': u'2',
'city__name': u'Joburg, Central',
'supplier__phone_number': u'02299944444',
'supplier__website': None,
'supplier__price_list': u'',
'supplier__email': u'[email protected]',
'unit__name': u'Gram',
'name': u'Rump Bone',
}}
今、テンプレートに情報を表示しようとしているのですが、苦労しています。テンプレートのコードは次のようになります。
{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{{ ingredient }}
{% endfor %}
<a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
Please search for an ingredient below
{% endif %}
テンプレートに「0」と表示されるだけですか?
私も試しました:
{% for ingredient in landing_dict.ingredients %}
{{ ingredient.cost }}
{% endfor %}
これでは結果すら表示されません。
おそらくもう 1 レベル深く繰り返す必要があると思ったので、これを試しました。
{% if landing_dict.ingredients %}
<hr>
{% for ingredient in landing_dict.ingredients %}
{% for field in ingredient %}
{{ field }}
{% endfor %}
{% endfor %}
<a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
Please search for an ingredient below
{% endif %}
しかし、何も表示されません。
何が間違っているのでしょうか?
ベストアンサー1
あなたのデータが -
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
メソッドを使用して、辞書の要素を取得できます。注意: Django テンプレートでは は使用しdata.items()
ません()
。また、一部のユーザーはvalues[0]
が機能しないと述べています。その場合は を試してくださいvalues.items
。
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
このロジックを特定の辞書に拡張できると確信しています。
ソートされた順序で辞書のキーを反復処理する- まず Python でソートし、次に Django テンプレートで反復処理とレンダリングを行います。
return render_to_response('some_page.html', {'data': sorted(data.items())})
テンプレートファイル内:
{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}