Skip to main content
 首页 » 编程设计

python之HTML 代码在模板中显示为文本

2025年05月04日8unruledboy

我有一个这样的模板:

{% extends "index.html" %} 
 
{% block content %} 
{% if post %} 
    <p> Post id: {{post.id}} </p> 
    Post title: {{post.post_title}}  
    Post: {{post.post_body | safe}}  
 
{% endif %} 
 
{% endblock content %} 

我的 post.post_body 是

<code> Hello World! </code> 

问题是,当页面被呈现时,代码标签也会出现,但它们并没有呈现为 HTML 标签。如果我检查呈现的 html,我会看到:

<p>&lt;code&gt; Hello World! &lt;/code&gt;</p> 

如何将这些标签呈现为 HTML 标签?

请您参考如下方法:

除了使用 safe 过滤器,您应该使用标签 {% autoescape off %} 和 {% endautoescape %} 包装变量。