Skip to main content
 首页 » 编程设计

python之如何在 webapp2 页面上正确显示来自 ndb.TextProperty 的 html 数据

2025年05月04日21txw1958

我需要你的帮助在我的 webapp2 页面上显示呈现的 html,其中数据来自 ndb TextProperty。在下面的示例中,我插入了

<b>foo</b> 

我转到开发服务器的数据存储查看器并确认存储的是上面的值。但是,当我在 Chrome 中加载页面时,它显示的就像我插入到 TextProperty 中的内容,而不是呈现的版本。我从 Chrome 查看源代码,发现我得到了这段代码:

&lt;b&gt;foo&lt;/b&gt; 

我该如何纠正它?

下面是详细信息。

我的模型如下:

Models.py 
========= 
from google.appengine.ext import ndb 
class MyPosts(ndb.Model): 
slug = ndb.StringProperty(indexed=True) 
content = ndb.TextProperty(indexed=False) 

我可以在我的模型中插入一堆 html 代码(只有 body 标签中的代码)。

这是我的 Controller 。当我取回记录时,查询工作正常。此外,路径没有问题,因为页面加载成功。

Controller.py 
============= 
import os 
from google.appengine.ext.webapp import template 
import webapp2 
from Models import MyPosts 
class ViewMyPost(webapp2.RequestHandler): 
def get(self,title): 
    ds = MyPosts.query(MyPosts.slug == title).fetch(1) 
    content = str(ds[0].content) 
    template_values = { 
        'body': content, 
    } 
    path = os.path.join(os.path.dirname(__file__), 'views/myview.html') 
    self.response.out.write(template.render(path, template_values)) 

这是我的看法。 {{ body }} 的值由我的 Controller 提供。

myview.html 
=========== 
<html> 
<head> 
    <title>My Page</title> 
</head> 
<body> 
    {{ body }} 
</body> 
</html> 

插入的数据: 我创建了一个简短的例程,为我的 TextProperty 插入一条具有以下值的记录

<b>foo</b> 

预期结果: 我希望页面显示 foo,这是用 TextProperty 字段的值直接替换 {{ body }}。

实际结果: 替换会发回我查询的整个 TextProperty 的值。但是,我以某种方式将标签转换如下:

&lt;b&gt;foo&lt;/b&gt; 

我在这里错过了什么?提前致谢!

请您参考如下方法:

这是一个简单的修复。

在 View 中,我添加了“|safe”过滤器。而不是 {{ body }},它现在看起来像这样 {{ body|safe }}。

myview.html 
=========== 
<html> 
<head> 
    <title>My Page</title> 
</head> 
<body> 
    {{ body|safe }} 
</body> 
</html> 

这是关于安全过滤器的文档 https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#safe