Jinja2 + Django: global functions and filters
Global functions are functions available for use in all Jinja2 templates. The advantage of using global functions is that the template can execute any piece of code and show the result of the function or simply process it later in the logic of the code template. The concept of filters is inherited from the Django template engine. Filters receive the results of the previous function or variable value, process it and returned back.
Global functions
Global functions are functions available for use in all Jinja2 templates. The advantage of using global functions is that the template can execute any piece of code and show the result of the function or simply process it later in the logic of the code template. The concept of filters is inherited from the Django template engine. Filters receive the results of the previous function or variable value, process it and returned back.
Global function has its own definition and implementation. We put the definition into the project settings.py and the definition in a separate file, with other global Jinja2 template engine functions. I personally use jinja_lib.py.
We write for example a global function get_current_date () which returns a formatted string with the current date.
In settings.py we define function name and the module in which it resides:
JINJA2_GLOBALS = {
"get_current_date": "project.main.jinja_lib.get_current_date",
}
In jinja_lib.py goes the function implementation:
def get_current_date():
import datetime
return datetime.date.today().strftime("%d.%m.%Y")
Now, we can call this function from the template:
Today is {{ get_current_date() }}.
Jinja2, unlike Django template engine, has the ability to pass function parameters. For example, we will write a function that detects wheter the visitor uses Internet Explorer. This can be detected from the request object that should be globally visible to all templates.
JINJA2_GLOBALS = {
"get_current_date": "project.main.jinja_lib.get_current_date",
"is_internet_explorer": "project.main.jinja_lib.is_internet_explorer",
}
In jinja_lib.py we implement the function:
def is_internet_explorer(request):
return request.META.get("HTTP_USER_AGENT", "").find("MSIE") != -1
This function can be called from the template as follows:
{% if is_internet_explorer(request) %}
Internet Explorer? Let's get serious!
{% else %}
Good! It isn't Internet Explorer.
{% endif %}
Thus, global functions are extremely useful and improve the overall functionality of the template engine to a new level.
Filters
The concept of filters is inherited from the Django template engine. Filters receive the result of the previous function or variable value, process it and return back. Filters can be chained so the result of a filter is passed to the next filter.
Although filters somewhat loose the sense because of the global functions, using it can increase the readability of the code in templates.
We will write a filter that formats the DateTime object into a string. To use the filter, it should be first declared in settings.py:
JINJA2_FILTERS = {
"project.main.jinja_lib.format_datetime",
}
In jinja_lib.py goes the implementation:
def format_datetime(value, format="%d.%m.%Y %H:%M"):
try:
return value.strftime(format)
except ValueError:
return u"Error: Invalid format."
We declared an optional parameter which specifies the format to be used to format a DateTime object. At the end, the filter in template is used as following:
Timestamp of the object: {{ item.timestamp | format_datetime() }}
Timestamp of the object, date only: {{ item.timestamp | format_datetime("%d.%m.%Y") }}
Featured projects
Open source
We support open source software. We will implement it where ever it's possible.
Portal for weekend tourism vikendi.com
Community of internet shops svimi.net
Solar plant supervisory system solar-cybro.com