templating

Jinja2 is the flask templating language; heavily inspired by Python and Django

Template Variables are passed in as named parameters by the render_template ft

Basics

{{ to insert }}

`

`

{# comment #}

Control

{% for topic in NAVBAR_LIST %}
    <div> {{topic}} </div>
    <div> {{topic}} </div>
{% endfor %}
{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}

Filters

Basically pipes like helpers in handlebars

{{ companies|tojson }} #turn companies into json

BLOCKS

Extend to leave common elements

You can override and fill in blocks

layout.html

<!doctype html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}">
        {% endblock %}
    </head>
    <body>
        <div id="content">
            {% block content %}{% endblock %}        </div>
    </body>
</html>

index.html

{% extends "layout.html" %}
{% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='admin.css') }}">
{% endblock %}
{% block body %}
  <h1>Overview</h1>
  <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>
{% endblock %}

Macros

{% macro input(name, value='', type='text', size=20) -%}
    <input type="{{ type }}" name="{{ name }}" value="{{
        value|e }}" size="{{ size }}">
{%- endmacro %}

The macro can then be called like a function in the namespace:

<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>

Linking with url_for

No Blueprint

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(username)

print(url_for('profile', username='John Doe'))
{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}
{{url_for('login')}} 
/login
{{url_for('profile', username='John Doe')}} #/user/John%20Doe

If there was a blueprint named main, us'main.login'

Last updated