我可以从 django 模板访问字典中的特定键值吗? [英] Can I access specific key values in dictionary from django template?

查看:34
本文介绍了我可以从 django 模板访问字典中的特定键值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何 get() 函数来代替?

Is there any get() function for this instead?

{% for key, value in choices.items %} 
  <li>{{key}} - {{value}}</li>
{% endfor %}

从 python 我有 get() 函数来从特定键获取值.但是我找不到相应的方法来使用 django 模板标签来做到这一点.所以我想知道这可能吗?我需要获取特定值,因为使用循环会在 html 源代码中添加很多新行.

From python I have the get() function to get values from a specific key. But I couldn't find a corresponding way to do that with django template tags. So I wonder is it possible? I need to get specific values since using loops adds a lot of new lines in the html source.

还是应该先处理好视图内部的输出再发送给模板,哪种方法更好?

Or should take care of the output inside the view before sending it out to the template, which method is better?

推荐答案

您可以使用 {{choices.items.key }} 来访问特定的 dict 元素.

You can use {{ choices.items.key }} to access a specific dict element.

尽管如此,没有理由关心 HTML 代码中的空格;典型的最终用户在阅读它时没有真正的业务,如果他很好奇,他总是使用 DOM 查看器或通过 HTML 美化器运行它.

There is no reason to care about whitespace in the HTML code though; the typical end-user has no real business in reading it and if he's curious he an always use a DOM viewer or run it through a HTML beautifier.

这篇关于我可以从 django 模板访问字典中的特定键值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆