前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django: custom template tags

django: custom template tags

原创
作者头像
刀枪不入de王二花
修改2022-09-27 15:33:49
3120
修改2022-09-27 15:33:49
举报
文章被收录于专栏:BETTERBETTER

要件

自定义template tags

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

2,自定义tag

代码语言:python
复制
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

代码语言:javascript
复制
{% 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

代码语言:javascript
复制
{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1,在app下,(view同级)建文件夹【templatetags】
  • 2,自定义tag
  • 3,使用 HTML load filters
  • 补充:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档