django--自定义过滤器

本文深入探讨了Django模板中使用模板过滤器时如何处理不同类型的字符串,包括未加工字符串、安全字符串和需要转码的字符串。通过具体实例展示了如何自定义模板过滤器,并确保正确处理字符串类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

in your project

polls/
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py


in your template

{% load poll_extras %}

near the top of your module

from django import template

register = template.Library()

实例:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()


@register.filter
@stringfilter
def lower(value):
    return value.lower()

If you’re writing a template filter that only expects a string as the firstargument, you should use the decoratorstringfilter. This will convert an object to its string value before being passed to your function.


进阶:(不好理解,我大概翻译一下)

需要注意的是,3种string类型能被传送进模版代码

(1)未加工的字符串(Raw strings):原生的python的str或者unicode的类型,输出的时候,输出时,如果自动转码功能生效,则会自动转码,否则状态不会发生变化。

(2)安全字符串(Safe string):已经被标记为安全,做了必要的转码,其一般用于含有原始HTML的输出,确定在客户端原样阐释

(3)被标记为“需要转码”的字符串(Strings marked as "needing escaping"):无论它们在不在自动转码块里,总是会在输出的时候转码,这些字符串只被转码一次


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值