企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
### Navigation - [index](# "General Index") - [modules](# "Python Module Index") | - [next](# "tornado.escape — Escaping and string manipulation") | - [previous](# "tornado.web — RequestHandler and Application classes") | - [Tornado 4.4.dev1 documentation](#) » - [Web framework](#) » # `tornado.template` — Flexible output generation A simple template system that compiles templates to Python code. Basic usage looks like: ~~~ t = template.Template("<html>{{ myvalue }}</html>") print t.generate(myvalue="XXX") ~~~ [`Loader`](# "tornado.template.Loader") 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 %} {% block student %} <li>{{ escape(student.name) }}</li> {% end %} {% end %} </ul> </body> </html> ### bold.html {% extends "base.html" %} {% block title %}A bolder title{% end %} {% block student %} <li><span style="bold">{{ escape(student.name) }}</span></li> {% end %} ~~~ Unlike most other template systems, we do not put any restrictions on theexpressions you can include in your statements. `if` and `for` blocks gettranslated exactly into Python, so you can do complex expressions like: ~~~ {% for student in [p for p in people if p.student and p.age > 23] %} <li>{{ escape(student.name) }}</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 [`RequestHandler`](# "tornado.web.RequestHandler"), override [`RequestHandler.get_template_namespace`](# "tornado.web.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 [`escape()`](# "tornado.escape.xhtml_escape"), [`url_escape()`](# "tornado.escape.url_escape"),[`json_encode()`](# "tornado.escape.json_encode"), and [`squeeze()`](# "tornado.escape.squeeze") to all templates by default. Typical applications do not create [`Template`](# "tornado.template.Template") or [`Loader`](# "tornado.template.Loader") instances byhand, but instead use the [`render`](# "tornado.web.RequestHandler.render") and[`render_string`](# "tornado.web.RequestHandler.render_string") methods of[`tornado.web.RequestHandler`](# "tornado.web.RequestHandler"), which load templates automatically basedon the `template_path`[`Application`](# "tornado.web.Application") setting. Variable names beginning with `_tt_` are reserved by the templatesystem and should not be used by application code. ### Syntax Reference 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 between `apply`and `end`: ~~~ {% 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. `{% 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 [`Application`](# "tornado.web.Application")or [`Loader`](# "tornado.template.Loader").: ~~~ {% autoescape xhtml_escape %} {% autoescape None %} ~~~ `{% block *name* %}...{% end %}` 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 %} ~~~ `{% comment ... %}`A comment which will be removed from the template output. Note thatthere is no `{% end %}` tag; the comment goes from the word `comment`to the closing `%}` tag.`{% extends *filename* %}`Inherit from another template. Templates that use `extends` shouldcontain one or more `block` tags to replace content from the parenttemplate. Anything in the child template not contained in a `block`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` and `else` 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 [`UIModule`](# "tornado.web.UIModule"). The output of the `UIModule` isnot escaped: ~~~ {% module Template("foo.html", arg=42) %} ~~~ `UIModules` are a feature of the [`tornado.web.RequestHandler`](# "tornado.web.RequestHandler")class (and specifically its `render` method) and will not workwhen the template system is used on its own in other contexts. `{% raw *expr* %}`Outputs the result of the given expression without autoescaping.`{% set *x* = *y* %}`Sets a local variable.`{% try %}...{% except %}...{% else %}...{% finally %}...{% end %}`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[`filter_whitespace`](# "tornado.template.filter_whitespace") 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*)[[source]](#) A compiled template. We compile into Python from the given template_string. You can generatethe template from variables with generate(). Construct a Template. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"><li><strong>template_string</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – the contents of the template file.</li><li><strong>name</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – the filename from which the template was loaded(used for error message).</li><li><strong>loader</strong> (<a class="reference internal" href="#tornado.template.BaseLoader" title="tornado.template.BaseLoader"><em>tornado.template.BaseLoader</em></a>) – the <a class="reference internal" href="#tornado.template.BaseLoader" title="tornado.template.BaseLoader"><code class="xref py py-obj docutils literal"><span class="pre">BaseLoader</span></code></a> responsible for this template,used to resolve <code class="docutils literal"><span class="pre">{%</span> <span class="pre">include</span> <span class="pre">%}</span></code> and <code class="docutils literal"><span class="pre">{%</span> <span class="pre">extend</span> <span class="pre">%}</span></code>directives.</li><li><strong>compress_whitespace</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/functions.html#bool" title="(in Python v3.4)"><em>bool</em></a><span class="link-target"> [https://docs.python.org/3.4/library/functions.html#bool]</span>) – Deprecated since Tornado 4.3.Equivalent to <code class="docutils literal"><span class="pre">whitespace="single"</span></code> if true and<code class="docutils literal"><span class="pre">whitespace="all"</span></code> if false.</li><li><strong>autoescape</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – The name of a function in the templatenamespace, or <code class="docutils literal"><span class="pre">None</span></code> to disable escaping by default.</li><li><strong>whitespace</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – A string specifying treatment of whitespace;see <a class="reference internal" href="#tornado.template.filter_whitespace" title="tornado.template.filter_whitespace"><code class="xref py py-obj docutils literal"><span class="pre">filter_whitespace</span></code></a> for options.</li></ul></td></tr></tbody></table> Changed in version 4.3: Added `whitespace` parameter; deprecated `compress_whitespace`. `generate`(***kwargs*)[[source]](#) Generate this template with the given arguments. *class *`tornado.template.``BaseLoader`(*autoescape='xhtml_escape'*, *namespace=None*, *whitespace=None*)[[source]](#) 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. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"><li><strong>autoescape</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – The name of a function in the templatenamespace, such as “xhtml_escape”, or <code class="docutils literal"><span class="pre">None</span></code> to disableautoescaping by default.</li><li><strong>namespace</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#dict" title="(in Python v3.4)"><em>dict</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#dict]</span>) – A dictionary to be added to the default templatenamespace, or <code class="docutils literal"><span class="pre">None</span></code>.</li><li><strong>whitespace</strong> (<a class="reference external" href="https://docs.python.org/3.4/library/stdtypes.html#str" title="(in Python v3.4)"><em>str</em></a><span class="link-target"> [https://docs.python.org/3.4/library/stdtypes.html#str]</span>) – A string specifying default behavior forwhitespace in templates; see <a class="reference internal" href="#tornado.template.filter_whitespace" title="tornado.template.filter_whitespace"><code class="xref py py-obj docutils literal"><span class="pre">filter_whitespace</span></code></a> for options.Default is “single” for files ending in ”.html” and ”.js” and“all” for other files.</li></ul></td></tr></tbody></table> Changed in version 4.3: Added `whitespace` parameter. `reset`()[[source]](#) Resets the cache of compiled templates. `resolve_path`(*name*, *parent_path=None*)[[source]](#) Converts a possibly-relative path to absolute (used internally). `load`(*name*, *parent_path=None*)[[source]](#) Loads a template. *class *`tornado.template.``Loader`(*root_directory*, ***kwargs*)[[source]](#) A template loader that loads from a single root directory. *class *`tornado.template.``DictLoader`(*dict*, ***kwargs*)[[source]](#) A template loader that loads from a dictionary. *exception *`tornado.template.``ParseError`(*message*, *filename=None*, *lineno=0*)[[source]](#) Raised for template syntax errors. `ParseError` instances have `filename` and `lineno` attributesindicating the position of the error. Changed in version 4.3: Added `filename` and `lineno` attributes. `tornado.template.``filter_whitespace`(*mode*, *text*)[[source]](#) Transform whitespace in `text` according to `mode`. 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. New in version 4.3. © Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.