This blog is the continuation of my previous one that you can find here. As I explained before, Jinja is a fast, expressive, extensible, Python based templating engine. In addition to variables and macros, you can exploit other functionalities to get the best out of it.
Comments
Comments are useful to add information for other template designers or yourself, or to hide some pieces of code for debugging. To use comments you use this syntax:
{# <comment> #}
Filters
You can modify variables with filters. Filters are separated from the variable by a pipe symbol (|
) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next. You use this syntax to apply filters:
{{ <variable> | <filter> | <filter> }}
Filters that accept arguments have parentheses around the arguments, just like a function call:
{{ <variable> | <filter>(<arguments>) }}
Useful Filters
The list of Jinja filters is huge, but here I show the most common and useful:
- abs, it returns the absolute value of the argument
- capitalize, capitalize a value where the first character will be uppercase, all others lowercase
- lower, converts a value to lowercase
- upper, converts a value to uppercase
- first, it returns the first item of a sequence
- last, it returns the last item of a sequence
- join, it returns a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string by default, but you can define it with as an optional parameter
- trim, strips leading and trailing white spaces
Example Code
Now I will show you some of the filters in action.
Let’s see the abs filter:
{% set neg_number = -3 %}
{{ neg_number | abs }}
This should result in the positive number 3:
3
What about lists and strings manipualtion:
{% set some_list = ['hello', 'how', 'are', 'YOU'] %}
{{ some_list | first | capitalize }}
{{ some_list | last | lower }}
In this case the result it’s:
Hello
you
At last, let’s see what join does:
{% set some_list = ['hello', 'how', 'are', 'you', '?'] %}
{{ some_list | join(' ') }}
The result of this transformation will be:
hello how are you ?