Template Syntax

Now that we’ve seen a simple example of templates in action, let’s go into a bit more detail about how they work. Templates in Tornado are simply text files marked up with Python expressions and control sequences. The syntax of Tornado templates is fairly straightforward and simple. Users familiar with Django, Liquid, or similar frameworks will find a lot of similarities, and should find it easy to pick up.

In Simple Example: Poem Maker Pro, we showed how to use the render method in a web application to send HTML to the browser. You can try out the templating system outside of a Tornado application by importing the template module in the Python interpreter, and printing the output directly.

>>> from tornado.template import Template
>>> content = Template("<html><body><h1>{{ header }}</h1></body></html>")
>>> print content.generate(header="Welcome!")
<html><body><h1>Welcome!</h1></body></html>

Interpolating Expressions

In Example 2-1, we demonstrated the use of double curly braces to interpolate the value of Python variables into a template. It turns out that you can put any Python expression inside double curly braces. Tornado will insert a string containing whatever that expression evaluated to into the output. Here are a few examples of what’s possible:

>>> from tornado.template import Template
>>> print Template("{{ 1+1 }}").generate()
2
>>> print Template("{{ 'scrambled eggs'[-4:] }}").generate()
eggs
>>> print Template("{{ ', '.join([str(x*x) for x in range(10)]) ...

Get Introduction to Tornado now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.