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"):无论它们在不在自动转码块里,总是会在输出的时候转码,这些字符串只被转码一次