Main Content

Jinja2 - Flask templating

Archive - Originally posted on "The Horse's Mouth" - 2015-10-11 17:22:06 - Graham Ellis

So far, we've only done simple inserts in our template - but there may be a requirement to do more - for example to insert a whole table of values. And this requires programatic elements in our template.

Whilst it would be nice if we could simply include Python code in our template (Like Ruby on Rails does with Ruby), this approach isn't practical as HTML is inherently space insignificant and Python is space significant and the whole thing would end up pretty awkward. By using a separate templating language (Jinja2) other things can be added in ... and those things in the base language which are not a good idea in the template can be left out.

The jinja2 templaing system / language allows us to insert variables as we've done so far in early examples, and it allow conditionals and loops too. Futrthermore, it supports template nesting. Note that you call up the inner template by name - that knows the name of its parent, which is then rendered with the child inserted at the marked point. You may feel it would be more natural to call up the parent from the controller, but by calling up the child you can easily and quickly request what you need without the requirement to understand or specify the template structure therein.

Here's sample controller code:

  @app.route("/<word>")
  def greet(word):
    return render_template('features.html',
      simple = "This is my title",
      several = ["Tom","Dick","Harry"],
      cookable = "Maybe <b>bold</b> text",
      links = [{"url":"http://www.wellho.net","title":"Well House Consultants"},
        {"url":"http://www.wellhousemanor.co.uk","title":"Well House Manor"}])


Full file [here]

And how it renders:



Here's the 'features.html' template:

  {% extends "base.html" %}
  {% block maincontent %}
  <b>Straight data inserts</b><br/><br />
  <em>Simple</em>: {{simple}}<br /><br />
  <em>Several</em>: {{several}}<br /><br />
  <em>Cookable</em>: {{cookable}}<br /><br />
  <em>links</em>: {{links}}<br /><br />
  <b>Using Jinja2 to reformat it</b><br/><br />
  <em>Several</em>:
  <ol>
  {% for item in several %}
    <li>How about {{item}}</li>
  {% endfor %}
  </ol>
  <em>Cookable</em>: {{cookable|safe}}<br /><br />
  <em>links</em>:
  <ul>
  {% for item in links %}
    <li>How about {{item.url}} for
    <a href={{item.url}} target=xyz>{{item.title}}</a></li>
  {% endfor %}
  </ul>
  {% endblock %}


Full file [here]

And here's the sample parent template that could be used right across the application:

  <html>
  <head>
  <title>A Well House demo</title>
  </head>
  <body>
  <i>This is the general template shared on may pages</i><hr />
  {% block maincontent %} {% endblock %}
  <hr />
  <i>This is the genarel footer
  </body>
  </html>


Full file [here]

See http://jinja.pocoo.org/docs/dev/templates/