【发布时间】:2013-07-22 00:34:06
【问题描述】:
我需要您的帮助来在我的 webapp2 页面上显示呈现的 html,数据取自 ndb TextProperty。在下面的示例中,我插入了
<b>foo</b>
我去了开发服务器的数据存储查看器并确认上面的值是存储的值。但是,当我在 Chrome 中加载页面时,它会显示为我插入到 TextProperty 中的内容,而不是呈现的版本。我从 Chrome 中查看了源代码,发现我收到了这段代码:
<b>foo</b>
如何改正?
以下是详细信息。
我的模型如下:
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.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 }} 的值由我的控制器提供。
myview.html
===========
<html>
<head>
<title>My Page</title>
</head>
<body>
{{ body }}
</body>
</html>
插入数据: 我创建了一个简短的例程,为我的 TextProperty 插入具有以下值的记录
<b>foo</b>
预期结果: 我希望页面显示 foo,这是用 TextProperty 字段的值直接替换 {{ body }}。
实际结果: 替换发回我查询的整个 TextProperty 的值。但是,不知何故,我将标签转换如下:
<b>foo</b>
我在这里缺少什么?提前致谢!
【问题讨论】:
-
这是一个简单的修复。在视图中,我添加了“|safe”过滤器。它现在看起来像 {{ body|safe }} 而不是 {{ body }}。 myview.html ===========
我的页面 {{ body|safe }} 这是关于安全过滤器的文档docs.djangoproject.com/en/dev/ref/templates/builtins/… -
很高兴您找到了解决方案。也许您可以回答自己的问题并批准答案,这样它就不会出现在未回答的类别中。
标签: python google-app-engine google-cloud-datastore webapp2