Website development often calls for reuse of pages. For instance, when you open your Citibank account after login the welcome page you see is same what other bank customers see but its customized with your name and settings. Do you think Citi creates so many web pages for all its customers? Well, they use, what’s called as template. Template is a layout or a skeleton that separates content from presentation and helps in mass production of web pages..

Control Statements in Templates

Tornado supports templates with expressions and control statements; straight from Tornadoweb, “Control statements are surronded by {% and %}, e.g., {% if len(items) > 2 %}. Expressions are surrounded by {{ and }}, e.g., {{ items[0] }}.”

In the above example, we have created a template (template.html) that requires a scalar value for title and a dictionary for listing dictionary items in the form of a table (List data types also work well in Tornado templates). The python code provide these values in the code line

self.render(‘template.html’, title=’Articles’, dict=articles)


tornado templates example

Run-time Template Generation and Compiling Templates

Let’s now understand two important methods in Tornado templates, how do they work and how are they implemented:

  1. Template()
  2. Loader()

Template() – helps in generating a template at run time. For instance, there is a web page with lesser content and that need not be rendered quite often, we can utilize this Template method.

Loader() – helps in compiling and caching templates from a predefined location of your machine. Compiling and caching improves performance of web server while rendering web pages.

Example 2

In example 2,

t = Template(“<html>{{ name }}</html>”) — generates template at run time

self.write(loader.load(“template.html”).generate(name=”John”))  — template is compiled, cached and loaded