Jinja2 - Custom Filters

Posted on 09-18-2018 by superadm1n

When using Jinja2 as your template engine you will no doubt eventually use a filter to control the output of what jinja is rendering for you.

An example, lets say that you are storing raw HTML in your applications database and you want to render that html directly into your page. You can use the "safe" filter to let jinja know that whatever you are rendering is known safe to enter directly into your html.

 

Default filters are limited

Although the default filters jinja provides do cover much of the scenerios you will need to use a filter for there are still some cases where you will need to write a custom filter to get jinja to behave exactly like you want to.

 

Example

Lets say that you have a string of undetermined length, it could be 10 characters or 10,000 words but no matter the length you want to display at maximum 50 characters.

 

Creating the Function

The first thing we will need to do is write a function that accepts a string as an argument and returns the first 50 characters of that string. Below is that function.

def textlimit(text):
    return text[0:50]

This text will take any string as an argument and at maximum return the first 50 characters of that string. This function can be placed in some sort of utility module within our web application, its placement will vary based on the structure of your application.

 

Configuring our Function as a Jinja Filter

This next step can vary based on what framework you are using so this is based on a Flask application. In order to link that function as a Jinja filter, in the initialization of the application we will need to import that function and pass it to our application. Lets say that we put our function in a module named jinjafilters below is an example of configuring the filter.

from flask import Flask
from jinjafilters import textlimit

app = Flask(__name__)

# Application initilization options

app.jinja_env.filters['textlimit'] = textlimit

# Other application initilization options

At this point jinja wil be able to use that function as a filter.

 

Using our new filter

Now we can use our filter just like any other by adding a pipe and using the name we gave it which was 'textlimit'. Lets say that were passing a variable called 'myText' when rendering our template and we want to limit its output to only 50 characters, below is an example snippit of a template using that filter.

<p>
  The output begins with: "{{ myText|textlimit }}"
</p>

This will truncate whatever text is contained in 'myText' to 50 characters and display add it into our html page when rendered.


Leave a Comment:

Search