What IS Jinja
Short introduction to Jinja
Jinja is a modern and designer-friendly templating language for Python, modeled after Django’s templates. It is fast, widely used, and secure with the optional sandboxed template execution environment. Jinja is basically an engine used to generate HTML or XML returned to the user via an HTTP response.
For those who have not been exposed to a templating language before, such languages essentially contain variables as well as some programming logic, which when evaluated (or rendered into HTML) are replaced with actual values.
Why do we need Jinja?
Sandboxed Execution - It provides a protected framework for automation of testing programs, whose behavior is unknown and must be investigated.
HTML Escaping - Jinja has a powerful automatic HTML Escaping, which helps to prevent Cross-site Scripting (XSS Attack). There are special characters like >,<,&, etc. which carry special meanings in the templates. So, if you want to use them as regular text in your documents then, replace them with entities. Not doing so might lead to XSS-Attack.
Template Inheritance - This feature helps us to generate new pages starting from a base template that we inherit a common structure.
Jinja Environment
Being a Python library, Jinja requires Python to run and expose the features. If you're not sure if Python is installed, just open a terminal and type python --version
. The output should be something like this:
How to get Jinja2
To start playing with it, just open a terminal and type:
Jinja in action
Simple runtime replace
The engine will replace the inner token with value Jinja2. This is quite useful when we use this block for different token values.
Lists iteration
In web development, we can have cases when a list should be displayed on the page: registered users, for instance, or a simple list of options. In Jinja, we can use a for structure
as bellow:
In Jinja, we can iterate with ease, using a for block:
Template Inheritance
Templates usually take advantage of inheritance, which includes a single base template that defines the basic structure of all subsequent child templates. You use the tags { extends } and { block } to implement inheritance.
Let's take a look at a real sample:
Parent HTML - saved as base.html
The Child template - saved as child.html
When Jinja loads child.html
, the { extends }
block informs the engine to merge the base.html
template with the content provided by child.html
.
{ block title }
becomesMySample
{ block content }
becomesCool content here
Here is the final HTML generated by Jinja:
Links & Resources
Jinja - official website
Jinja Template - a curated list with starters published on Github
Last updated