Sta*_*tan 207 python django templates dictionary
mydict = {"key1":"value1", "key2":"value2"}
Run Code Online (Sandbox Code Playgroud)
在Django模板中查找字典值的常规方法是{{ mydict.key1 }}, {{ mydict.key2 }}.如果键是循环变量怎么办?即:
{% for item in list %} # where item has an attribute NAME
{{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
mydict.item.NAME失败.如何解决这个问题?
cul*_*rón 326
编写自定义模板过滤器:
from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
Run Code Online (Sandbox Code Playgroud)
(我.get这样使用,如果没有密钥,它就不会返回.如果你这样做,dictionary[key]它会提高一个KeyError.)
用法:
{{ mydict|get_item:item.NAME }}
Run Code Online (Sandbox Code Playgroud)
Pau*_*ipp 46
从循环中的字典中获取键和值:
{% for key, value in mydict.items %}
{{ value }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我发现这更容易阅读,它避免了特殊编码的需要.无论如何,我通常需要键中的键和值.
Yuj*_*ita 33
你不能默认.点是属性查找/键查找/切片的分隔符/触发器.
点在模板渲染中具有特殊含义.变量名中的点表示查找.具体来说,当模板系统遇到变量名中的点时,它会按以下顺序尝试以下查找:
- 字典查找.示例:foo ["bar"]
- 属性查找.示例:foo.bar
- 列表索引查找.示例:foo [bar]
但是你可以制作一个允许你传入参数的过滤器:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters
@register.filter(name='lookup')
def lookup(value, arg):
return value[arg]
{{ mydict|lookup:item.name }}
Run Code Online (Sandbox Code Playgroud)
对我来说,创建一个template_filters.py在我的应用程序中命名的 python 文件,内容如下
# coding=utf-8
from django.template.base import Library
register = Library()
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
Run Code Online (Sandbox Code Playgroud)
用法就像 culebrón 所说的:
{{ mydict|get_item:item.NAME }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124864 次 |
| 最近记录: |