Tornado – Template – Extends

With the background of Tornado-Templates let’s solve bigger problems in web development. It maybe less complex to change welcome messages or usernames on a home page of the website, but it’s not so easy to cater to customization. For instance, gmail web client provides Settings and Themes that are customized for users. Even thought the base template (mail format, mail importance or chat pane) is same, Themes may differ based on customization set by the user.

Handling of customize is really trivial with Tornado. Here’s how..


{%extends "templateinheritance.html" %}
{% block header %}
<table border="1">
<tr>
<td>Article2</td>
<td>Author2</td>
</tr>
{% end %}

view raw

custom.html

hosted with ❤ by GitHub


<html>
<head>
<title>Articles</title>
</head>
<body>
<h4>Articles available</h4>
<table border="1">
<tr>
<td>Article1</td>
<td>Author1</td>
</tr>
<tr>
<td>Article2</td>
<td>Author2</td>
</tr>
<tr>
<td>Article3</td>
<td>Author3</td>
</tr>
</table>
<h4> {{ username }}, you've read these articles</h4>
{% block header %}
<table border="1">
<tr>
<td>None</td>
<td>None</td>
</tr>
{% end %}
</body>
</html>


import tornado.ioloop
import tornado.web
import time
class ItWorks(tornado.web.RequestHandler):
def get(self):
self.write("It Works!!")
class Article(tornado.web.RequestHandler):
def get(self):
self.render('custom.html', username='John')
## title and dict is handled by template.html
application = tornado.web.Application([
(r"/", ItWorks),
(r"/articles", Article),
],debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

In the above example, when custom.html is loaded, templateinheritance.html is first loaded as custom.html extends it. templateinheritance.html acts as a base template. {% block header %} and {% end %} block ensures customized information for username=John is addressed on the web page. So, with the base template, only the articles available for reading are shown but with custom.html ensures that when John logs-in he also gets to see the books he has read.

Base Template


Extended Template

One thought on “Tornado – Template – Extends

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.