python - 如何将值传递给 Tornado 中的模板

标签 python templates python-2.7 tornado

我有一个模板,它显示了很多从服务器传递过来的值,我的问题是如何将这些值传递给模板文件。 我的处理程序代码如下: AdminHandler 类(tornado.web.RequestHandler): def get(self, *args, **kwargs): #响应一个get方法 #self.write("AdminHandler::Inside GET 函数")

    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'] %} {% 结束 %}

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

raise ParseError("未知运算符: %r"% 运算符) ParseError:未知运算符:“项目[‘用户名’]” 错误:root:500 GET/admin (127.0.0.1) 3.27ms

最佳答案

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

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 模板的更多信息,请查看 this tutorial当然还有 Tornado templates documentation .

关于python - 如何将值传递给 Tornado 中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461585/

相关文章:

c# - ContentPresenter 的异常行为

c++ - 具有成员函数指针的模板的默认值

c++ - 在 `using Base::operator T` 是模板类型参数的情况下,是否允许 `T`?

python - pdb:如何显示当前行,而不是在上一个列表之后继续?

Python/Pandas 减去一列中的数字

python - 如何为 64 位 Windows 和 Python 2.7 安装 ZBar?

python - 从 CSV 中删除尾随空格

python - Scrapy 从动态表中提取数据

python - 操纵 Blackjack 中 A 的值(Python)

Python 相当于 PHP 的空合并运算符和速记三元运算符?