Templating

Most WSGI applications are responding to HTTP requests to serve content in HTMLor other markup languages. Instead of directly generating textual content fromPython, the concept of separation of concerns advises us to use templates. Atemplate engine manages a suite of template files, with a system of hierarchyand inclusion to avoid unnecessary repetition, and is in charge of rendering(generating) the actual content, filling the static content of the templateswith the dynamic content generated by the application.

As template files aresometimes written by designers or front-end developers, it can be difficult tohandle increasing complexity.

Some general good practices apply to the part of the application passingdynamic content to the template engine, and to the templates themselves.

  • Template files should be passed only the dynamiccontent that is needed for rendering the template. Avoidthe temptation to pass additional content “just in case”:it is easier to add some missing variable when needed than to removea likely unused variable later.
  • Many template engines allow for complex statementsor assignments in the template itself, and manyallow some Python code to be evaluated in thetemplates. This convenience can lead to uncontrolledincrease in complexity, and often make it harder to find bugs.
  • It is often necessary to mix JavaScript templates withHTML templates. A sane approach to this design is to isolatethe parts where the HTML template passes some variable contentto the JavaScript code.

Jinja2

Jinja2 is a very well-regarded template engine.

It uses a text-based template language and can thus be used to generate anytype of markup, not just HTML. It allows customization of filters, tags, tests,and globals. It features many improvements over Django’s templating system.

Here some important HTML tags in Jinja2:

  1. {# This is a comment #}
  2.  
  3. {# The next tag is a variable output: #}
  4. {{title}}
  5.  
  6. {# Tag for a block, can be replaced through inheritance with other html code #}
  7. {% block head %}
  8. <h1>This is the head!</h1>
  9. {% endblock %}
  10.  
  11. {# Output of an array as an iteration #}
  12. {% for item in list %}
  13. <li>{{ item }}</li>
  14. {% endfor %}

The next listings are an example of a web site in combination with the Tornadoweb server. Tornado is not very complicated to use.

  1. # import Jinja2
  2. from jinja2 import Environment, FileSystemLoader
  3.  
  4. # import Tornado
  5. import tornado.ioloop
  6. import tornado.web
  7.  
  8. # Load template file templates/site.html
  9. TEMPLATE_FILE = "site.html"
  10. templateLoader = FileSystemLoader( searchpath="templates/" )
  11. templateEnv = Environment( loader=templateLoader )
  12. template = templateEnv.get_template(TEMPLATE_FILE)
  13.  
  14. # List for famous movie rendering
  15. movie_list = [[1,"The Hitchhiker's Guide to the Galaxy"],[2,"Back to future"],[3,"Matrix"]]
  16.  
  17. # template.render() returns a string which contains the rendered html
  18. html_output = template.render(list=movie_list,
  19. title="Here is my favorite movie list")
  20.  
  21. # Handler for main page
  22. class MainHandler(tornado.web.RequestHandler):
  23. def get(self):
  24. # Returns rendered template string to the browser request
  25. self.write(html_output)
  26.  
  27. # Assign handler to the server root (127.0.0.1:PORT/)
  28. application = tornado.web.Application([
  29. (r"/", MainHandler),
  30. ])
  31. PORT=8884
  32. if __name__ == "__main__":
  33. # Setup the server
  34. application.listen(PORT)
  35. tornado.ioloop.IOLoop.instance().start()

The base.html file can be used as base for all site pages which arefor example implemented in the content block.

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
  2. <html lang="en">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <link rel="stylesheet" href="style.css" />
  6. <title>{{title}} - My Webpage</title>
  7. </head>
  8. <body>
  9. <div id="content">
  10. {# In the next line the content from the site.html template will be added #}
  11. {% block content %}{% endblock %}
  12. </div>
  13. <div id="footer">
  14. {% block footer %}
  15. &copy; Copyright 2013 by <a href="http://domain.invalid/">you</a>.
  16. {% endblock %}
  17. </div>
  18. </body>

The next listing is our site page (site.html) loaded in the Pythonapp which extends base.html. The content block is automatically setinto the corresponding block in the base.html page.

  1. {% extends "base.html" %}
  2. {% block content %}
  3. <p class="important">
  4. <div id="content">
  5. <h2>{{title}}</h2>
  6. <p>{{ list_title }}</p>
  7. <ul>
  8. {% for item in list %}
  9. <li>{{ item[0]}} : {{ item[1]}}</li>
  10. {% endfor %}
  11. </ul>
  12. </div>
  13. </p>
  14. {% endblock %}

Jinja2 is the recommended templating library for new Python web applications.

Chameleon

Chameleon Page Templates are an HTML/XML templateengine implementation of the Template Attribute Language (TAL),TAL Expression Syntax (TALES),and Macro Expansion TAL (Metal) syntaxes.

Chameleon is available for Python 2.5 and up (including 3.x and PyPy), andis commonly used by the Pyramid Framework.

Page Templates add within your document structure special element attributesand text markup. Using a set of simple language constructs, you control thedocument flow, element repetition, text replacement, and translation. Becauseof the attribute-based syntax, unrendered page templates are valid HTML and canbe viewed in a browser and even edited in WYSIWYG editors. This can makeround-trip collaboration with designers and prototyping with static files in abrowser easier.

The basic TAL language is simple enough to grasp from an example:

  1. <html>
  2. <body>
  3. <h1>Hello, <span tal:replace="context.name">World</span>!</h1>
  4. <table>
  5. <tr tal:repeat="row 'apple', 'banana', 'pineapple'">
  6. <td tal:repeat="col 'juice', 'muffin', 'pie'">
  7. <span tal:replace="row.capitalize()" /> <span tal:replace="col" />
  8. </td>
  9. </tr>
  10. </table>
  11. </body>
  12. </html>

The <span tal:replace=”expression” /> pattern for text insertion is commonenough that if you do not require strict validity in your unrendered templates,you can replace it with a more terse and readable syntax that uses the pattern${expression}, as follows:

  1. <html>
  2. <body>
  3. <h1>Hello, ${world}!</h1>
  4. <table>
  5. <tr tal:repeat="row 'apple', 'banana', 'pineapple'">
  6. <td tal:repeat="col 'juice', 'muffin', 'pie'">
  7. ${row.capitalize()} ${col}
  8. </td>
  9. </tr>
  10. </table>
  11. </body>
  12. </html>

But keep in mind that the full _<span tal:replace=”expression”>Default Text</span>_syntax also allows for default content in the unrendered template.

Being from the Pyramid world, Chameleon is not widely used.

Mako

Mako is a template language that compiles to Pythonfor maximum performance. Its syntax and API are borrowed from the best parts of othertemplating languages like Django and Jinja2 templates. It is the default templatelanguage included with the Pylons and Pyramid webframeworks.

An example template in Mako looks like:

  1. <%inherit file="base.html"/>
  2. <%
  3. rows = [[v for v in range(0,10)] for row in range(0,10)]
  4. %>
  5. <table>
  6. % for row in rows:
  7. ${makerow(row)}
  8. % endfor
  9. </table>
  10.  
  11. <%def name="makerow(row)">
  12. <tr>
  13. % for name in row:
  14. <td>${name}</td>\
  15. % endfor
  16. </tr>
  17. </%def>

To render a very basic template, you can do the following:

  1. from mako.template import Template
  2. print(Template("hello ${data}!").render(data="world"))

Mako is well respected within the Python web community.

References

[1]Benchmark of Python WSGI Servers

原文: https://docs.python-guide.org/scenarios/web/