当我访问/ admin / newpost时,我希望我的edit.html模板能够呈现并显示我的表单字段。相反,我得到一个没有错误的空白页面。但是,当我查看源代码时,我会看到以下内容。
<Template '/edit.html'>
我没有收到任何错误,因此没有堆栈跟踪。
我的代码和模板位于
之下这是我的代码:
import os
import webapp2
import config
import jinja2
from google.appengine.ext import db
import fix_path
import config
import static
import wtforms
from wtforms.ext.appengine.db import model_form
from wtforms import Form, TextField, validators
def render_template(template_name, template_vals=None, theme=None):
template_path = os.path.join(os.path.dirname(__file__) , \
"themes", theme or config.theme)
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path))
return env.get_template(template_name, template_vals or {})
class BlogPost(db.Model):
#The URL path to the blog post. Posts have a path if they are published.
path = db.StringProperty()
title = db.StringProperty(required=True, indexed=False)
body = db.TextProperty(required=True)
published = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def render(self):
template_vals = {
'config': config,
'post': self,
}
return render_template("post.html", template_vals)
form = model_form(BlogPost, Form)
class PostForm(form):
pass
class PostHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_to_response(
self,
template_name,
template_vals=None,
theme=None
):
template_name = "admin/%s" % template_name
self.response.out.write(render_template(
template_name, template_vals, theme))
def render_form(self, form):
self.render_to_response("edit.html", {'form': form})
def get(self):
self.render_form(PostForm())
app = webapp2.WSGIApplication([('/admin/newpost', PostHandler)],
debug=True)
这是我的模板:
{% extends "base.html" %}
{% block title %}Testing New Post Template{% endblock %}
{% block body %}
<form method="post" action="">
<table>
<div>{{ form.title.label }}: {{ form.title(class="css_class") }}</div>
{% if form.title.errors %}
<ul class="errors">{% for error in form.name.errors %}<li>{{ error }}</li>{% endfor %}</ul>
{% endif %}
<div>{{ form.body.label }}: {{ form.body() }}</div>
{% if form.body.errors %}
<ul class="errors">{% for error in form.body.errors %}<li>{{ error }}</li>{% endfor %}</ul>
{% endif %}
</table>
<input type="submit" />
</form>
{% endblock %}
我的app.yaml文件
application: cmwo-blog
version: 1
runtime: python27
api_version: 1
threadsafe: no
handlers:
- url: /admin/.*
script: admin.app
login: admin
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /static/([^/]+)/(.*)
static_files: themes/\1/static/\2
upload: themes/[^/]+/static/.*
- url: .*
script: static.app
builtins:
- remote_api: on
libraries:
- name: webapp2
version: "2.5.1"
- name: jinja2
version: latest
答案 0 :(得分:2)
我不使用Jinja,但您的render_template
方法似乎并没有实际渲染模板。它调用env.get_template
,它可能会获得一个模板对象,但后来需要调用一些东西来实际呈现该模板 - 快速查看the documentation,你应该这样做:
template = env.get_template(template_name)
return template.render(**(template_vals or {}))