无法使用Jinja2渲染GAE数据存储中的数据

2 投票
1 回答
572 浏览
提问于 2025-04-16 14:39

我不知道自己哪里做错了。我在GAE的数据库里有一些数据条目。我已经导入了Jinja2,想用它在页面上显示这些数据库条目。我创建了一个快捷函数来调用Jinja2的渲染函数,代码大概是这样的:

def render_template(response, template_name, vars=dict()):
    template_dirs = [os.path.join(root(), globals['templates_root'])]
    env = Environment(loader=FileSystemLoader(template_dirs))
    try:
        template = env.get_template(template_name)
    except TemplateNotFound:
        raise TemplateNotFound(template_name)
    content = template.render(vars)
    response.response.out.write(content)

所以,我只需要传递给这个函数一个模板文件名和一个包含变量的字典(如果有的话)。我这样调用这个函数:

class MainHandler(webapp.RequestHandler):
    def get(self, *args, **kwargs):
        q = db.GqlQuery("SELECT * FROM Person")
        persons = q.fetch(20)
        utils.render_template(self, 'persons.html', persons)

模型Person看起来就是这样,没什么特别的:

class Person(db.Model):
    first_name = db.StringProperty()
    last_name = db.StringProperty()
    birth_date = db.DateProperty()

当我尝试把persons字典传给render_template时,它报了个错:

TypeError: cannot convert dictionary update sequence element #0 to a sequence

而且没有渲染出来。当我把空的{}作为persons参数传入时,它可以渲染,但显然没有我的数据。 我到底哪里做错了?我相信我遗漏了什么小细节,但我不知道具体是什么。谢谢!

1 个回答

2

你现在是把一个实体列表传给了 render_template 函数,而不是传一个字典。你可以试试这样做:utils.render_template(self, 'persons.html', {'persons': persons})

撰写回答