5

我有一个模板,它显示了许多从服务器传递的值,我的问题是如何将这些值传递给模板文件。我的处理程序代码如下: class AdminHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): #respond to a get method #self.write("AdminHandler:: Inside GET function")

    userName = "Alwin Doss"
    welcomeMessage = "Good evening are you enjoying kids dance"
    items = {}
    items["userName"] = userName
    items["welcomeMessage"] = welcomeMessage


    self.render("web/admin.html", title="Admin Page", items=items)

我的模板代码如下: {% items['userName'] %} {% items['welcomeMessage'] %} {% end %}

问题是我无法在模板文件中访问这些值。我收到以下错误:

raise ParseError("unknown operator: %r" % operator) ParseError: unknown operator: "items['userName']" ERROR:root:500 GET /admin (127.0.0.1) 3.27ms

4

1 回答 1

11

这是一个类似于您似乎正在做的演示。查看模板的语法并查看块的不同{% %}用途{{ }}。这段代码:

from tornado import template

t = template.Template('''\
{% for user in users %} 
    {{ user['userName'] }} 
    {{ user['welcomeMessage'] }} 
{% end %}
''')

# create first user and append to a user list
users = []
user = { "userName" : "Alwin Doss",
        "welcomeMessage" : "Good evening are you enjoying kids dance"}
users.append(user)

# create and append second user
user = { "userName" : "John Smith",
        "welcomeMessage" : "Good evening, JS"}
users.append(user)

# render the template and output to console
print t.generate(users = users)

产生这个输出:

Alwin Doss 
Good evening are you enjoying kids dance 

John Smith 
Good evening, JS 

有关 Tornado 模板的更多信息,请查看本教程,当然还有Tornado 模板文档

于 2012-05-05T14:21:30.120 回答