Skip to Main Content
Introduction to Tornado
book

Introduction to Tornado

by Michael Dory, Allison Parrish, Brendan Berg
March 2012
Beginner to intermediate content levelBeginner to intermediate
138 pages
3h 21m
English
O'Reilly Media, Inc.
Content preview from Introduction to Tornado

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)]) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Microservices Patterns Video Edition

Microservices Patterns Video Edition

Chris Richardson
Spark: The Definitive Guide

Spark: The Definitive Guide

Bill Chambers, Matei Zaharia

Publisher Resources

ISBN: 9781449312787Errata Page