display dictionary file inside for loop in django template

南笙酒味 提交于 2019-12-11 14:24:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!