【问题标题】:display dictionary file inside for loop in django template在 django 模板中的 for 循环内显示字典文件
【发布时间】:2018-05-28 19:25:55
【问题描述】:

我有以下字典:

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

【问题讨论】:

  • 这里需要一个 django 模板tag。这将使这个问题变得相当简单。
  • 您没有在上下文中定义list_upper 有什么原因吗?您不必为 for 循环在模板中进行疯狂的编码。

标签: python django django-templates


【解决方案1】:

像这样创建一个标签文件:

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

我是从头开始做这一切的,所以那里可能存在格式或语法错误,但按照我之前链接的文档,这应该可以让你到达你需要的地方。

【讨论】:

  • 这是我第一次使用模板标签。感谢您的即时回复。它对我有用。
  • @CarlosFabiera 很高兴它成功了。我将它插入到我自己的测试项目中,并意识到我需要进行一些更改才能使其正常运行。我假设你必须做同样的 xD
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2011-09-19
  • 2021-10-17
相关资源
最近更新 更多