问题
I have the following dictionary:
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 %}
I want to display the d[value] inside input text value attribute when values from d[key] is found in list_upper
How can I call {% if d.keys in x %} in django template?
回答1:
Create a tag file like this:
# 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
Assuming your view passes in context that looks like this:
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]
}
Then in your template you can do this:
{% 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 %}
I'm doing this all from my head so there might be a formatting or syntax bug in there somewhere but following the documentation I linked earlier this should get you to where you need to be.
来源:https://stackoverflow.com/questions/47817872/display-dictionary-file-inside-for-loop-in-django-template