Learn the templating language(Jinja 2) in 10 minutes
Jinja is a designer-friendly templating language that is simple and easy-to-use.
Jinja2 is being is used in APITemplate.io as the templating language. It can be used together with HTML to render dynamic templates and generate PDF documents.
In this tutorial, we will show you the basics of Jinja2 and syntax.
Templating basics
Jinja2 is dependent on two source materials which are template and dynamic context data(JSON).
They combine and create a template as a result of which the final document is rendered.
Template variables are enclosed in {{
... }}
Sample JSON
{
"product": "Apple Juice",
"made_in" : "Singapore"
}
Jinja2 Template
The product is {{product}}
Output
The product is Apple Juice
A template is referred to as a unit of source code that consists of variables that can be changed by the values which are given in when the template is rendered in the real-time environment.
Variables(Context data/JSON) play a vital role in templates and are useful for dynamic data. These variables can be of any type like a number, string, or any list data.
Jinja2 Syntax
There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:
{%
...%}
is used for statements that can be used for the writing core knowledge of the code.{{
...}}
is used for printing variables/expressions to the template output{#
...#}
is used for comments to represent the code explanation.
Variable Substitution
A variable is a data component that takes values during the runtime of a program and outputs values from the context is called Variables in programming.
The simplest one is made of text with variables. This simple template is listed below.
Sample JSON
{
"name": "Mike"
}
Jinja2 Template (Jinja2 encloses its variables in two curly brackets on each side.)
Hello {{ name }}
In this example, we have only one variable, which is represented as Name. If we set the variable dynamically in the template to be rendered is Mike. The above-mentioned template will display the output as follows:
Output
Hello Mike
Statements and Conditions
Flow control and conditional statements are used to alter the flow of a program
To check the life span of the product
Sample JSON
{
"product": "Apple Juice",
"life_span": 180,
"made_in" : "Singapore"
}
Jinja2 Template (Comparison operators)
{% if life_span > 160 and life_span < 180 %}
{{product}} is expiring soon!
{% elif life_span >= 180 %}
{{product}} has expired!
{% else %}
It's perfect
{% endif %}
Output
Apple Juice has expired!
{%
... %}
these are the placeholders from which all the conditions are executed.
The if
statement of Jinja2 resembles Python's If
statement. It is used to detect whether the variable is perfectly defined, it's not empty, or false. In Jinja2, other than the if
statement, elif
and else
are also used for branching out.
Syntax
{% if <condition> %}
{% elif <condition> %}
{% else %}
{% endif %}
- The
{% if %}
statement is the primary building block to evaluate conditions. - The
{% if %}
statement is typically used in conjunction with the{% elif %}
and{% else %}
statements to evaluate more than one condition. - An
{% if %}
statement with an argument variable evaluates to true if a variable exists and is not empty or if the variable holds a True boolean value. If
block will always end with{% endif %}
.
Comparison operators
Operator | Description | Example |
---|---|---|
== | Compares two objects for equality. | val1 == val2 |
!= | Compares two objects for inequality. | val1 != val2 |
> | Greater than | val1 > val2 |
>= | Greater than and equal to | val1 >= val2 |
< | Less than | val1 < val2 |
<= | Less than and equal to | val1 <= val2 |
Comparison functions
Jinja2 Template (Comparison functions)
{% if gt(life_span, 160) and lt(life_span, 180) %}
{{product}} is expiring soon!
{% elif gte(life_span, 180) %}
{{product}} has expired!
{% else %}
It's perfect
{% endif %}
Output
Apple Juice has expired!
Alternatively, you can use our comparison functions
Operator | Description | Example |
---|---|---|
gt | Greater than | gt(val1,val2) |
gte | Greater than and equal to | gte(val1,val2) |
lt | Less than | lt(val1,val2) |
lte | Less than and equal to | lte(val1,val2) |
Logical operators
Operator | Description |
---|---|
and | Returns true if both statements are true |
or | Returns true if one of the statements is true |
not | Negate the result, returns false if the result is true |
Simple Loop
Sample JSON
{
"products": ["Apple Juice", "Orange Juice", "Pineapple Juice"]
}
Jinja2 Template
<ul>
{% for product in products %}
<li>{{ product }}</li>
{% endfor %}
</ul>
Output
<ul>
<li>Apple Juice</li>
<li>Orange Juice</li>
<li>Pineapple Juice</li>
</ul>
The syntax for
... endfor
is used for repeating a certain set of statements for a particular number of times.
- The
{% for %}
...{% endfor %}
statement iterates over items on a dictionary, list, tuple or string variable. - The
{% for %}
statement syntax is{% for <reference> in <variable> %}
, where<reference>
is assigned a new value from<variable>
on each iteration. - Depending on the nature of a variable there can be one or more references (e.g. for a list one reference, for a dictionary two references).
Nested Loop
We will learn in this section how to iterate through a list of dictionaries, arrays, or the hash table by combining for loop
with some dictionary examples to show how Jinja2 works with a nested loop.
A nested loop is based on two layers. One is outer loop
and other one is inner loop
.
Sample JSON
{
"fruit": [
{
"key": 1,
"value": "Apple"
},
{
"key": 2,
"value": "Banana"
},
{
"key": 3,
"value": "Orange"
}
]
}
Jinja2 Template
{% for fruit in fruit %}
{% for key, value in fruit.items() %}
{{key}} : {{value}}
{% endfor %}
{% endfor %}
Output
key : 1 value : Apple
key : 2 value : Banana
key : 3 value : Orange
APITemplate.io Filters/Functions
Introduction
Filters are special functions that take a data structure or variable in a template and render it in a slightly different format. Filters in jinja2 are used to modify data that is provided as variables to the dynamically written code.
We support filters to generate QRCode, barcode and HTML table from a json array.
Filters Syntax
The syntax that we apply for filters to variables is the vertical line |
that is also called pipe
, it may have various arguments in parentheses ( )
to separate the different candidates.
The syntax for using filter looks like
{{ variable | filter }}
.
We can apply various filters to the same variable at the same time. The output of one filter can be applied to another filter using a statement. In most cases, we can provide more than one variable. Like ,{{ [z,y,x] | join }}
. In most cases, we provide more than one argument. Like, {{ [x, y, z] | join | upper }}
.
The delimiters such as {{...}} and pipes | which are used to enclose variables and define filter expressions
Render QR Code
To render a value into a QRCode
{{json_field_or_value
| render_qrcode(style="css styles
")}}
Sample JSON
{
"email": "hello@apitemplate.io",
"website": "https://apitemplate.io",
}
Jinja2 Template
{{website | render_qrcode(style='width: 100px;height:100px;background: white;')}}
QR code for {{website}}
Output
Render Bar Code
To render a value into a bar code
{{json_field_or_value
| render_barcode(type="barcode_type
", style="css styles
", quiet_zone =quiet zone
, font_size=font size
, text_distance=text distance
, module_width=module width
, module_height=module height
) }}
Sample JSON
{
"document_id": "889856789012"
}
Jinja2 Template
{{document_id | render_barcode(type='ean13', style='height: 100px;', quiet_zone=0, font_size=10, text_distance=5, module_width=0.2, module_height=15.0)}}
Barcode for {{document_id}}
Output
The Parameters
Only the type
parameter is required. The rest are optional.
type
The following are the supported barcode formats:
BarCode Type | Description |
---|---|
ean8 | EAN8 |
ean13 | EAN13 |
ean | EAN13 |
gtin | EAN14 |
ean14 | EAN14 |
jan | JAN |
upc | UPCA |
upca | UPCA |
isbn | ISBN13 |
isbn13 | ISBN13 |
gs1 | ISBN13 |
isbn10 | ISBN10 |
issn | ISSN |
code39 | Code39 |
pzn | PZN |
code128 | Code128 |
itf | ITF |
gs1_128 | Gs1_128 |
quiet_zone
: Distance on the left and on the right from the border to the first (last) barcode module in mm as float. Defaults to 0font_size
: Font size of the text under the barcode in pt as integer. Font size zero suppresses text. Defaults to 10text_distance
: Distance between the barcode and the text under it in mm as float. Defaults to 5.0module_width
: The width of one barcode module in mm as float. Defaults to 0.2module_height
: The height of the barcode modules in mm as float. Defaults to 15.0
Render Table
Render a json array into a HTML table
{{json_array
| render_table(table_class="css class
")}}
Sample JSON
{
"title": "json list",
"items": [
{
"item_name": "product 1",
"price": "USD 200.00"
},
{
"item_name": "product 2",
"price": "USD 300.00"
}
]
}
Jinja2 Template
{{items | render_table(table_class='table')}}
Output
Render JSON
Render a JSON object into a JSON in the HTML
{{json_object
| json}}
Datetime - Parse Datetime(from a String)
Convert a string to datetime
{{ strptime
(strdatetime
) }}
Learn more at here
Sample JSON
{
"website": "https://apitemplate.io",
"document_id": "889856789012",
"due_date": "2022-08-16T15:57:31.325116Z"
}
Jinja2 Template (Parsing and reformat a datetime)
{{strftime(strptime(due_date,"%Y-%m-%dT%H:%M:%S.%fZ"),"%d/%m/%y")}}
Output
16/08/22
Datetime - Format Datetime
Format datetime
{{ strftime
(vardatetime
, format
) }}
Learn more at here
Sample JSON
{
"website": "https://apitemplate.io",
"document_id": "889856789012",
"due_date": "2022-08-16T15:57:31.325116Z"
}
Jinja2 Template (Parsing and reformat a datetime)
{{strftime(strptime(due_date,"%Y-%m-%dT%H:%M:%S.%fZ"),"%d/%m/%y")}}
Output
16/08/22
Datetime - Parse Unix epoch time
{{ epoch_to_datetime
(epoch_time
, timezone_hour
) }}
epoch_time
: The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT)timezone_hour
: default to zero. Example, if your timezone is UTC+8, use 8 for the parameter.
Sample JSON
{
"website": "https://apitemplate.io",
"document_id": "889856789012",
"due_date": "2022-08-16T15:57:31.325116Z",
"created_at": 1665494864
}
Jinja2 Template (Parsing and reformat a datetime)
{{ strftime(epoch_to_datetime( created_at , 8),"%y-%m-%d") }}
Output
22-10-11
Format Currency/Integer
Apply the given values to a printf-style format string, like string % values.
Find out more at here
Sample JSON
{
"gross_total": 2000.50,
"batchNumber": "736628"
}
Jinja2 Template (Parsing and reformat a datetime)
{{ "${:,.2f}".format(gross_total) }}
Output
$2,000.50
Other Useful Functions/Filters
Capitalize
This filter capitalizes the first character of the variable that is provided in the example.
If we provide any data in the JSON and then when we want to capitalize the first word of that sentence then we need to apply this keyword in the filter template.
Syntax
{{variable|capitalize}}
Sample Data
{
"sentence": "mango is fruit"
}
Jinja2
{{sentence|capitalize}}
Output
Mango is fruit
Lower
This filter convert a value to lowercase.
Syntax
{{variable|lower }}
Sample JSON Data
{
"sentence": "Mango is a fruit"
}
Jinja2 Template
{{sentence|lower}}
Output
mango is a fruit
Title
This filter will capitalize the first character of each word that is provided in the example.
If we provide any data in the JSON and then when we want to capitalize the first character of each word of the sentence then we need to apply this keyword in the filter template.
Syntax
{{variable|title}}
Sample JSON Data
{
"sentence": "mango is fruit"
}
Jinja2 Template
{{sentence|title}}
Output
Mango Is Fruit
Upper
This filter will capitalize all the words of the sentence that is provided in the example.
If we provide any data in the JSON and then when we want to capitalize all words of the sentence then we need to apply this keyword in the filter template.
For example, if a variable contains Mike Is Good Person
the filter statement {{ variable | upper }}
outputs MIKE IS GOOD PERSON
on the output terminal.
Syntax
{{variable|upper}}
Sample JSON Data
{
"sentence": "Mango is a fruit"
}
Jinja2 Template
{{sentence|upper}}
Output
MANGO IS A FRUIT
Max
This filter will select which is the largest item in the variable that is given.
For example, if we have provided the list { 8, 9, 10, 11}
, the output that we'll get after providing the syntax {{variable|max}} will be 11
.
Syntax
{{variable | max}}
Sample JSON Data
{
"items": [1, 2, 3]
}
Jinja2 Template
{{integars|max}}
Output
3
Other Filters
- sum()
- max()
- min()
- first()
- last()
- map()
- length()
- random()
- upper()
- lower()
- title()
- abs()
- round()
- format()
- join()
- replace()
- urlencode()
- random()
More Functions(Filters) on official website
Conclusion
Want information on the template engine's syntax? Head over to the official Jinja2 website and documentation
A YouTube tutorial is also available for your convenience: - Jinja2 Templating Engine Tutorial by Mr. Rigden