[英]display dictionary file inside for loop in django template
我有以下字典:
d = {'21': 'test1', '11': 'test2'}
{% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %}
{% for x in list_upper.split %}
{% if x in dental_position %}
<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{display dict.value here}}">
{% else %}<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]">
{% endif%}
{% endfor %}
當在list_upper
找到d[key]
值時,我想在輸入文本值屬性中顯示d[value]
如何在Django模板中調用{% if d.keys in x %}
?
創建這樣的標記文件:
# tags.py
def is_dict_key(key, d):
return key in d
def get_dict_value(d, key):
try:
return d[key]
except KeyError as e:
print(e)
return None
假設您的視圖在如下所示的上下文中通過:
context = {
'dental_position': {21: 'test1', 11: 'test2'}
'list_upper': [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28]
}
然后,您可以在模板中執行以下操作:
{% load tags %}
{% for x in list_upper %}
{% if x|is_dict_key:dental_position %}
<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{dental_position|get_dict_value:x}}">
{% else %}
<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]">
{% endif%}
{% endfor %}
我從頭開始進行所有操作,因此某個地方可能存在格式或語法錯誤,但是按照我之前鏈接的文檔,這應該可以使您到達所需的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.