UI Modules

As we’ve seen, the templating system is lightweight but powerful. In practice, we’d like to follow the software engineering adage, Don’t Repeat Yourself. In order to eliminate redundant code, we can make sections of our templates modular. For example, pages that display lists of items can define a single module that renders the markup for each item. Alternatively, groups of pages that share a common navigation structure could render content from a shared module. Tornado’s UI Modules are especially helpful in these situations.

UI Modules are reusable components that encapsulate markup, style, and behavior for inclusion in a template. The page elements they define are typically reused across many templates or are included repeatedly in the same template. Modules themselves are simply Python classes that inherit from Tornado’s UIModule class and define a render method. When a template references a module with the {% module Foo(...) %} tag, Tornado’s template engine calls the module’s render method, which returns a string that replaces the module tag in the template. UI modules may also embed their own JavaScript and CSS in the rendered page, or specify additional JavaScript or CSS files to be included. You may define optional embedded_javascript, embedded_css, javascript_files and css_files methods to that end.

Basic Module Usage

In order to reference a module in your templates, you must declare it in the application’s settings. The ui_modules parameter expects a dictionary ...

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.