html模板代码<p>Dear {{ person_name|initial_letter_filter }}</p>
第一版
@register.filter(name='initial_letter_filter')#注册过滤器
@stringfilter #转为字符串
def initial_letter_filter(value):
'''
将首个字加粗
:param value:传入的值
:return:html代码
'''
first,other = value[0],value[1:]
result = '<strong>{}</strong>{}'.format(first,other)
return result
结果
与目标差距:输出字符被转义
解决方案:避免被转义
将filter加上is_safe标签@register.filter(name='initial_letter_filter',is_safe=True)#注册过滤器
我加了,但是没用
文档中有这么一句话
This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary.
这个标志告诉Django 如果"安全"的字符串传递到您的过滤,结果仍将是"安全",如果一个非安全字符串传递,如果必要Django 会自动转义它。
具体用法,在这个兄弟的博客里https://www.cnblogs.com/thunderLL/p/7645111.html被分析了,我也参照学习了他的,嗯。。有需要的跳吧
所以根据需求 选另一种方法 使用need_autoescape进行手动控制
@register.filter(name='initial_letter_filter',needs_autoescape=True)
def initial_letter_filter(text, autoescape=True):
first, other = text[0], text[1:]
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
result = '<strong>{}</strong>{}'.format(first, other)
return mark_safe(result)