You should take every effort to not use any programming logic within your Jinja templates but there are times where you have no choice and the best of the bad options you have available to you is to give Jinja access to a python function to grab data out of the database or do some other tasks. In this post I will be showing you how to give Jinja access to a python function within a flask application.



For this tutorial lets say that you need to preform a database query every time Jinja renders a template and it is not practical to do that within your route for some reason.


Creating our Function

The first thing we will need to do is write our function to preform the database operation. I often like to keep any functions that Jinja can access in its own module within my project so if you dont have a module like that within your project yet go ahead and create one and name it something like "".

Inside that module we will create our function, below is an example function in our jinja_functions module.

def first_5_completed_jobs():
    """Allows jinja to get 5 entries in our database."""

    return Table.query.filter_by(completed=True).limit(5).all()


Giving Jinja access to our function

In order to allow Jinja to use our newly created function we need to go to the initilization of our application, import our function, and pass it to Jinja. Below is an example of the initilization of a Flask application giving access to our function.

from flask import Flask
from jinja_functions import first_5_completed_jobs

app = Flask(__name__)

# Application initilization options

# Allow Jinja to use our db function

# Other application initilization options

Now everything is all good to go, below is an example snippit of a Jinja template that would utilize our function.

{% for job in first_5_completed_jobs() %}
      {{ job.title }}
{% endfor %}