我正在阅读有关自定义过滤器的 Django 文档。
并且.. 我看不出 is_safe 存在的原因。 https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping
当我编写一些示例然后尝试它们时,无论 is_safe 是 True 还是 False,结果总是相同的。
为什么要使用 is_safe?
这是我的代码
extra_tags.py
from django.template.defaultfilters import stringfilter
from django import template
import datetime
register = template.Library()
@register.filter(name='custom_lower')
@stringfilter
def lower(value):
is_safe = True
return '%sxx'%value
lower.is_safe = True;
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
@register.filter(name='custom_lf')
def initial_letter_filter(text, autoescape=None):
first, other = text[0], text[1:]
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
result = '<strong>%s</strong>%s' % (esc(first), esc(other))
return mark_safe(result)
initial_letter_filter.is_safe = False
initial_letter_filter.needs_autoescape = True
我的观点是,无论我编写 is_safe=True 还是 is_safe=False,结果都将是自动转义字符。我不明白为什么要使用 is_safe。
最佳答案
将 is_safe
与 mark_safe()
一起使用是多余的,这可能就是您看不到任何差异的原因。
正如您链接到的部分所述,在它谈论 mark_safe()
的地方:
There's no need to worry about the is_safe attribute in this case (although including it wouldn't hurt anything). Whenever you manually handle the auto-escaping issues and return a safe string, the is_safe attribute won't change anything either way.
is_safe
只是一种自动将函数的返回值标记为安全的方法,假定所有外部输入都已安全。 Django 仍然会自动转义输入的任何内容,但它不会尝试转义后来由您的函数添加的其他部分。
mark_safe()
证明无论输入是否安全,输出都是安全的 - 如果您要使用,则必须满足更严格的要求
关于python - 为什么要使用 is_safe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7665512/