Skip to content Skip to sidebar Skip to footer

Display Dictionary File Inside For Loop In Django Template

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

Solution 1:

Create a tag file like this:

# tags.pydefis_dict_key(key, d):
   return key in d

defget_dict_value(d, key):
  try:
      return d[key]
  except KeyError as e:
      print(e)
      returnNone

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 %}
       <inputtype="text" placeholder = "{{ x }}"class="form-control" name="tooth[]" value="{{dental_position|get_dict_value:x}}">
     {% else %}
       <inputtype="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.

Post a Comment for "Display Dictionary File Inside For Loop In Django Template"