在我的应用程序team/templatetags/teams_extras.py中,我有这个过滤器
from django import template
register = template.Library()
@register.filter(is_safe=True)
def quote(text):
return "« {} »".format(text)
Run Code Online (Sandbox Code Playgroud)
所以我将它用于我的视图team/templates/teams/show.html
{% extends './base.html' %}
{% load static %}
{% load teams_extras %}
...
<b>Bio :</b> {{ team.biography|quote }}
...
Run Code Online (Sandbox Code Playgroud)
但这是我页面上的结果:
« <p>The Miami Heat are an American professional basketball team based in Miami. The Heat compete in the National Basketball Association as a member of the league's Eastern Conference Southeast Division</p> »
Run Code Online (Sandbox Code Playgroud)
为什么 ?谢谢
医生说:
\n\n\n\n\n该标志告诉 Django,如果将 \xe2\x80\x9csafe\xe2\x80\x9d 字符串传递到过滤器中,结果仍将是 \xe2\x80\x9csafe\xe2\x80\x9d,如果是非安全字符串传入时,Django 会在必要时自动转义它。
\n
因此,尝试将安全值传递到您的过滤器中:
\n\n{{ team.biography|safe|quote }}\nRun Code Online (Sandbox Code Playgroud)\n\n或用户mark_safe:
\n\nfrom django.utils.safestring import mark_safe\n\n@register.filter()\ndef quote(text):\n return mark_safe("« {} »".format(text))\nRun Code Online (Sandbox Code Playgroud)\n\n和:
\n\n{{ team.biography|quote }}\nRun Code Online (Sandbox Code Playgroud)\n\n这应该有效。
\n