Django测试项目autoescape显示异常,如何调整项目解决该问题
Django autoescape显示异常问题解决
问题根源
你当前的heading变量是双重HTML转义后的字符串:'Hello &lt;i&gt;my&lt;/i&gt; World!'。即使开启{% autoescape off %},浏览器会先把&lt;解析成<,最终页面显示的是<i>my</i>文本,而非预期的斜体样式。
解决方案
根据你的实际场景,选择以下两种方式之一:
场景1:直接使用原始HTML内容
如果你的目标是显示Hello <i>my</i> World!(斜体的my),直接在视图中传入未转义的HTML字符串:
修改myworld/members/views.py:
def testing(request): template = loader.get_template('template.html') context = { 'heading': 'Hello <i>my</i> World!', } print(context) return HttpResponse(template.render(context, request))
模板中保留{% autoescape off %}即可,Django不会转义该变量,浏览器会正常解析<i>标签为斜体。
场景2:处理已转义的字符串
如果heading是从外部获取的已转义字符串(如&lt;i&gt;格式),需要先反转义再输出:
方式A:在视图中处理
使用Python内置的html.unescape进行反转义:
import html def testing(request): template = loader.get_template('template.html') raw_heading = 'Hello &lt;i&gt;my&lt;/i&gt; World!' context = { 'heading': html.unescape(raw_heading), } print(context) return HttpResponse(template.render(context, request))
模板中使用safe过滤器告诉Django该内容是安全的HTML:
{% autoescape off %} <h1>{{ heading|safe }}</h1> {% endautoescape %}
方式B:直接在模板中处理
使用Django的safe过滤器标记内容为安全HTML,此时可去掉{% autoescape off %}:
<h1>{{ heading|safe }}</h1>
内容的提问来源于stack exchange,提问作者AmirHesam
相关产品推荐
相关产品推荐

