Python程序教程

您现在的位置是:首页 >  Django

当前栏目

django: custom template tags

django,custom,template,tags
2025-04-11 08:57:58 时间

要件

自定义template tags

1,在app下,(view同级)建文件夹【templatetags】

2,自定义tag

app\templatetags\filters.py

from django import template

register = template.Library()
@register.filter(name='lookup')
def lookup(dict, arg:str, default=""):
    """从字典,通过key取value"""
    if str(arg) in dict:
        return dict[str(arg)]
    else:
        return default

@register.filter(name='get_item')     #处理等价于lookup
def get_item(dictionary, key):
    return dictionary.get(key)

3,使用 HTML load filters

{% load filters %}         // load: Loads a custom template tag set.

<div class="has-text-right">{{ dict_tax_rate|lookup:"tax_code" }}</div>

补充:

无参数function可以直接调用,用【.】,有参数,则需要自定义tags,如上述【lookup】

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation

{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}