Chapter 3. Extending Templates
In Chapter 2, we saw how the Tornado template system could be used to easily pass information from handlers to web pages, letting you keep your web markup clean while easily interpolating dynamic data. However, most sites will want to make use of repurposable content like headers, footers, and layout grids. In this chapter, we’ll take a look at how you can accomplish this by extending Tornado templates, or using UI modules.
Blocks and Substitutions
When you’ve taken the time to set up and lay out templates for your
web application, it only seems logical that you’d want to reuse your
frontend code as much as your backend Python, right? Fortunately, Tornado
lets you do just that. Tornado supports template inheritance through
extends and block statements, which give you the control and
flexibility to make fluid templates that can be repurposed as you see
fit.
To extend an existing template, you just need to put an {% extends "filename.html" %} at the top of the
new template file. For example, to extend a parent template (main.html here) into a new template, you’d just
use:
{% extends "main.html" %}This will let the new file inherit all the markup of main.html, and then overwrite content where desired. With this system, you can create master templates, switch in other subpages for special needs, and have both default and dynamic text and markup ready to go.
Basics of Blocks
Extending a template makes it easy to repurpose content you’ve previously written, but ...
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.
Read now
Unlock full access