Learning Python Network Programming

(Sean Pound) #1
Chapter 9

So what does render_template() do? Well, it looks in the templates folder for the
file supplied as the first argument, reads it, runs any processing instructions in the
file, then returns the processed HTML as a string. Any keyword arguments supplied
to render_template() are passed to the template and become available to its
processing instructions.


Looking at the templates, we can see they are mostly HTML, but with some extra
instructions for Flask, contained in {{ }} and {% %} tags. The {{ }} instructions
simply substitute the value of the named variable into that point of the HTML. So
for example the {{ func_name }} in docstrings.html substitutes the value of the
func_name value we passed to render_template().


The {% %} instructions contain logic and flow control. For example, the {% for func
in funcs %} instruction in index.html loops over values in funcs and repeats the
contained HTML for each value.


Finally, you may have spotted that templates allow inheritance. This is provided by
the {% block %} and {% extends %} instructions. In base.html we declare some
shared boilerplate HTML, then in the tag we just have a {% block body %}
instruction. In index.html and docstring.html, we don't include the boilerplate
HTML; instead we extend base.html, meaning that these templates will fill the
block instructions declared in base.html. In both index.html and docstring.
html, we declare a body block, the contents of which Flask inserts into the HTML in
base.html, replacing the matching {% block body %} there. Inheritance allows the
reuse of common code, and it can cascade through as many levels as needed.


There is a lot more functionality available in Jinja2 template instructions; check out
the template designer documentation for a full list at http://jinja.pocoo.org/
docs/dev/templates/.


Other templating engines


Jinja2 is certainly not the only templating package in existence; you can find a
maintained list of Python templating engines at https://wiki.python.org/moin/
Templating.


Like frameworks, different engines exist because of differing philosophies on what
makes a good engine. Some feel that logic and presentation should be absolutely
separate and that flow control and expressions should never be available in
templates, providing only value substitution mechanisms. Others take the opposite
tack and allow full Python expressions within template markup. Others, such as
Jinja2, take a middleground approach. And some engines use different schemes
altogether, such as XML-based templates or declaring logic via special HTML
tag attributes.

Free download pdf