python - GAE 上的 jinja2 在每次响应时写出 'None'

标签 python google-app-engine templates jinja2

无论处理程序的输出多么简单,我都会在每个响应的末尾得到一个 None 字符串。

这是我的处理程序代码:

class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    def render_response(self, _template, **context):
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)


class SimpleHandler(BaseHandler):
     def get(self):
        template_values = {
            'error' : "",
            'url' : os.path.basename(self.request.url)
        }

        self.render_response('temp.html', **template_values)

模板:

<!DOCTYPE html>
<html>
    <head>
        <title>Home</title> 
                <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    </head>
    <body>
        <div></div>
        <div>
            Test
        </div>
        <div>{{ error }}</div>
    </body>
</html>

最后输出

Test
None

在此之后,每个输出的末尾都包含字符串“None”。感谢帮助!!!

最佳答案

需要注意的是 None 将返回一个空值(参见 this answer )。为了处理它,你可以做这样的事情来确保只有存在错误时才会打印 error:

<html>
    <head>
        <title>Home</title> 
        <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    </head>
    <body>
        <div></div>
        <div>
            Test
        </div>
        <!-- Here we check to see 'error' is not null; if not, print -->
        {% if error %}
            <div>{{ error }}</div>
        {% endif %}
    </body>
</html>

关于python - GAE 上的 jinja2 在每次响应时写出 'None',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111772/

相关文章:

c++ - 如何将函数应用于可变列表的每个组件并返回可变列表?

c++ - 前端/后端设计 : how to absolutely dissociate the back-end from the front-end?

python - 如何缩放除最后一列之外的所有列?

python - 在 Google App Engine 中查找相对路径的好方法是什么?

java - 如何将 HashMap(作为对象属性)保存到数据存储区

python - Google App EngineSearch API 中的分页

c++ - 具有不完整 Value 参数的 Boost.Iterator Facade

python - Django 1.6 管理面板自定义

python - 如何让 "int"解析空白字符串?

java - GAE 开发服务器忽略 "threadsafe"标志