Jinja2¶
Jinja2 是一个非常受欢迎的模板引擎。
它使用基于文本的模板语言,因此可以用于生成任何类型的标记,而不仅仅是HTML。它允许定制过滤器、标签、测试和全局参数。它比Django的模板系统有很多改进。
以下是jinja2中的一些重要HTML标记:
{# This is a comment #} {# The next tag is a variable output: #} {{title}} {# Tag for a block, can be replaced through inheritance with other html code #} {% block head %} <h1>This is the head!</h1> {% endblock %} {# Output of an array as an iteration #} {% for item in list %} <li>{{ item }}</li> {% endfor %}
下面的列表是一个结合了Tornado Web服务器的网站示例。龙卷风的使用并不复杂。
# import Jinja2 from jinja2 import Environment, FileSystemLoader # import Tornado import tornado.ioloop import tornado.web # Load template file templates/site.html TEMPLATE_FILE = "site.html" templateLoader = FileSystemLoader( searchpath="templates/" ) templateEnv = Environment( loader=templateLoader ) template = templateEnv.get_template(TEMPLATE_FILE) # List for famous movie rendering movie_list = [[1,"The Hitchhiker's Guide to the Galaxy"],[2,"Back to future"],[3,"Matrix"]] # template.render() returns a string which contains the rendered html html_output = template.render(list=movie_list, title="Here is my favorite movie list") # Handler for main page class MainHandler(tornado.web.RequestHandler): def get(self): # Returns rendered template string to the browser request self.write(html_output) # Assign handler to the server root (127.0.0.1:PORT/) application = tornado.web.Application([ (r"/", MainHandler), ]) PORT=8884 if __name__ == "__main__": # Setup the server application.listen(PORT) tornado.ioloop.IOLoop.instance().start()
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="style.css" /> <title>{{title}} - My Webpage</title> </head> <body> <div id="content"> {# In the next line the content from the site.html template will be added #} {% block content %}{% endblock %} </div> <div id="footer"> {% block footer %} © Copyright 2013 by <a href="http://domain.invalid/">you</a>. {% endblock %} </div> </body>
site.htmlbase.htmlbase.html
{% extends "base.html" %} {% block content %} <p class="important"> <div id="content"> <h2>{{title}}</h2> <p>{{ list_title }}</p> <ul> {% for item in list %} <li>{{ item[0]}} : {{ item[1]}}</li> {% endfor %} </ul> </div> </p> {% endblock %}
Jinja2是新的python web应用程序的推荐模板库。