Welcome to a Flask tutorial covering a bit more about Jinja. We covered more of the Jinja basics earlier in this tutorial. This tutorial is a quick overview of the points I find to be most important from the Jinja documentation, that I have not yet covered in the earlier tutorials. Just like I recommend scrolling through the Bootstrap documentation once in a while, you should do the same here.
First on our docket: Filters. I find myself using these very often. These are very similar to your str()
, int()
, and replace()
commands in Python. For example, let's build a quick new page to run our Jinja samples through:
__init__.py
@app.route('/jinjaman/') def jinjaman(): try: return render_template("jinja-templating.html") except Exception as e: return(str(e))
Great, now we need the template:
templates/jinja-templating.html
{% extends "header.html" %} {% block body %} <body class="body"> <div class="container"> </div> </body> {% endblock %}
This will be our start. Next, let's pass a few vars from our __init__.py
file.
@app.route('/jinjaman/') def jinjaman(): try: data = [15, '15', 'Python is good','Python, Java, php, SQL, C++','<p><strong>Hey there!</strong></p>'] return render_template("jinja-templating.html", data=data) except Exception as e: return(str(e))
Next, let's reference this data in our templates/jinja-templating.html
file:
{% extends "header.html" %} {% block body %} <body class="body"> <div class="container"> {% for d in data %} <p>{{d}}</p> {% endfor %} <hr> {% if data[1]|int > 10%} <p>True!</p> {% endif %} <hr> <p>{{data[2]|replace('good','FREAKIN AWESOME!')}}</p> <hr> {% for lang in data[3].split(',') %} <p>{{lang}}</p> {% endfor %} <hr> {{data[4]|safe}} </div> </body> {% endblock %}
Sometimes, you may want to display raw Jinja code, you can do this with the raw tag, like so:
{% raw %} {% for item in seq %} {{ item }} {% endfor %} {% endraw %}
Next up, I would like to draw your attention to 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>
Finally, you should also brush up on the logic with Jinja, to be familiar with what your options are.
So those are just some quick pointers and additions to Jinja templating, using examples of things I have actually personally found myself using frequently. I still suggest you browse the docs from time to time, as things are changed and added. Next up, we're going to be discussing how to create dynamic links, which are called converters in Flask.