tornado.template — Flexible output generation¶
Basic usage looks like:
is a class that loads templates from a root directory and cachesthe compiled templates:
- loader = template.Loader("/home/btaylor")
- print loader.load("test.html").generate(myvalue="XXX")
We compile all templates to raw Python. Error-reporting is currently… uh,interesting. Syntax for the templates:
- ### base.html
- <html>
- <head>
- <title>{% block title %}Default title{% end %}</title>
- </head>
- <body>
- <ul>
- {% for student in students %}
- <li>{{ escape(student.name) }}</li>
- {% end %}
- {% end %}
- </ul>
- </body>
- </html>
- ### bold.html
- {% extends "base.html" %}
- {% block title %}A bolder title{% end %}
- <li><span style="bold">{{ escape(student.name) }}</span></li>
- {% end %}
Translating directly to Python means you can apply functions to expressionseasily, like the escape()
function in the examples above. You can passfunctions in to your template just like any other variable(In a , override RequestHandler.get_template_namespace
):
- ### Python code
- def add(x, y):
- return x + y
- template.execute(add=add)
- ### The template
- {{ add(1, 2) }}
We provide the functions , url_escape()
,, and squeeze()
to all templates by default.
Typical applications do not create or Loader
instances byhand, but instead use the andrender_string
methods of, which load templates automatically basedon the template_path
Application
setting.
Template expressions are surrounded by double curly braces: {{ … }}
.The contents may be any python expression, which will be escaped accordingto the current autoescape setting and inserted into the output. Othertemplate directives use {% %}
.
To comment out a section so that it is omitted from the output, surround itwith {# … #}
.
These tags may be escaped as {{!
, {%!
, and {#!
if you need to include a literal {{
, {%
, or {#
in the output.
{% apply function %}…{% end %}
Applies a function to the output of all template code betweenapply
andend
:- {% apply linkify %}{{name}} said: {{message}}{% end %}
Note that as an implementation detail apply blocks are implementedas nested functions and thus may interact strangely with variablesset via{% set %}
, or the use of{% break %}
or{% continue %}
within loops.- {% apply linkify %}{{name}} said: {{message}}{% end %}
{% autoescape function %}
Sets the autoescape mode for the current file. This does not affectother files, even those referenced by{% include %}
. Note thatautoescaping can also be configured globally, at the orLoader
.:
Indicates a named, replaceable block for use with{% extends %}
.Blocks in the parent template will be replaced with the contents ofthe same-named block in a child template.:- <!— base.html —>
<title>{% block title %}Default title{% end %}</title>
<!— mypage.html —>
{% extends "base.html" %}
{% block title %}My page title{% end %}
- <!— base.html —>
{% comment … %}
- A comment which will be removed from the template output. Note thatthere is no
{% end %}
tag; the comment goes from the wordcomment
to the closing%}
tag. {% extends filename %}
- Inherit from another template. Templates that use
extends
shouldcontain one or moreblock
tags to replace content from the parenttemplate. Anything in the child template not contained in ablock
tag will be ignored. For an example, see the{% block %}
tag. {% for var in expr %}…{% end %}
- Same as the python
for
statement.{% break %}
and{% continue %}
may be used inside the loop. {% from x import y %}
- Same as the python
import
statement. {% if condition %}…{% elif condition %}…{% else %}…{% end %}
- Conditional statement - outputs the first section whose condition istrue. (The
elif
andelse
sections are optional) {% import module %}
- Same as the python
import
statement. {% include filename %}
- Includes another template file. The included file can see all the localvariables as if it were copied directly to the point of the
include
directive (the{% autoescape %}
directive is an exception).Alternately,{% module Template(filename, *kwargs) %}
may be usedto include another template with an isolated namespace. {% module
expr %}
Renders a . The output of theUIModule
isnot escaped:- {% module Template("foo.html", arg=42) %}
UIModules
are a feature of thetornado.web.RequestHandler
class (and specifically itsrender
method) and will not workwhen the template system is used on its own in other contexts.- {% module Template("foo.html", arg=42) %}
{% raw
expr %}
- Outputs the result of the given expression without autoescaping.
{% set
x = y %}
- Sets a local variable.
- Same as the python
try
statement. {% while
condition %}… {% end %}
- Same as the python
while
statement.{% break %}
and{% continue %}
may be used inside the loop. {% whitespace
mode* %}
- Sets the whitespace mode for the remainder of the current file(or until the next
{% whitespace %}
directive). See for available options. New in Tornado 4.3.
Class reference¶
- class
tornado.template.
Template
(template_string, name="<string>", loader=None, compress_whitespace=None, autoescape="xhtml_escape", whitespace=None)¶
A compiled template.
We compile into Python from the given templatestring. You can generatethe template from variables with generate().
Construct a Template.
|参数:
|——-
|
- template_string ([_str]()) – the contents of the template file.
- name (str) – the filename from which the template was loaded(used for error message).
- loader () – the BaseLoader responsible for this template,used to resolve {% include %} and {% extend %}directives.
- compress_whitespace () – Deprecated since Tornado 4.3.Equivalent to whitespace="single" if true andwhitespace="all" if false.
- autoescape (str) – The name of a function in the templatenamespace, or None to disable escaping by default.
- whitespace () – A string specifying treatment of whitespace;see filter_whitespace for options.
在 4.3 版更改: Addedwhitespace
parameter; deprecatedcompresswhitespace
.generate
(kwargs)¶
Generate this template with the given arguments.
- _class
tornado.template.
BaseLoader
(autoescape='xhtml_escape', namespace=None, whitespace=None)¶
Base class for template loaders.
You must use a template loader to use template constructs like{% extends %}
and{% include %}
. The loader caches alltemplates after they are loaded the first time.
Construct a template loader.
|参数:
|——-
|
- autoescape () – The name of a function in the templatenamespace, such as “xhtml_escape”, or None to disableautoescaping by default.
- namespace (dict) – A dictionary to be added to the default templatenamespace, or None.
- whitespace () – A string specifying default behavior forwhitespace in templates; see filter_whitespace for options.Default is “single” for files ending in ”.html” and ”.js” and“all” for other files.
在 4.3 版更改: Addedwhitespace
parameter.load
(name, parent_path=None)¶
Loads a template.
reset
()¶
Resets the cache of compiled templates.
resolvepath
(_name, parent_path=None)¶
Converts a possibly-relative path to absolute (used internally).
- class
tornado.template.
Loader
(root_directory, _kwargs)¶
A template loader that loads from a single root directory.
- _class
tornado.template.
DictLoader
(dict, **kwargs)¶
A template loader that loads from a dictionary.
- exception
tornado.template.
ParseError
(message, filename=None, lineno=0)¶
Raised for template syntax errors.ParseError
instances havefilename
andlineno
attributesindicating the position of the error.
在 4.3 版更改: Addedfilename
andlineno
attributes.
tornado.template.
filterwhitespace
(_mode, text)¶
Transform whitespace in according tomode
.
Available modes are:
- all: Return all whitespace unmodified.
- single: Collapse consecutive whitespace with a single whitespacecharacter, preserving newlines.
- oneline: Collapse all runs of whitespace into a single spacecharacter, removing all newlines in the process.
4.3 新版功能.