loading...
Cover image for Jinja Template - Cheat Sheet and FREE Sample

Jinja Template - Cheat Sheet and FREE Sample

sm0ke profile image Sm0ke ・5 min read

Hello Coders,

This article presents a short introduction to Jinja Template system, a modern and designer-friendly templating language for Python, modeled after Django’s templates. Jinja is basically an engine used to generate HTML or XML returned to the user via an HTTP response.
To make this article more useful, I will present a free Jinja Template sample built from the popular Now UI Dashboard design (free version).


Thank you for reading! TL;DR; Links:


Jinja Template - Now UI Dashboard design, an open-source starter provided by AppSeed.


What is Jinja

Jinja is a library for Python used by popular web frameworks like Flask and Django to serve HTML pages in a secure and efficient way. Using a template engine is a common practice in web development, no matter the language or framework used to code the web application.

Jinja Environment

Being a Python library, Jinja requires Python to installed and usable via the terminal. We can check the Python installation by typing python --version. Once we are sure that Python is installed, Jinja can be installed via PIP, the official package manager for Python:

$ pip install jinja2

The most simple Jinja code snippet might be the following:

>>> from jinja2 import Template
>>> t = Template("Jinja {{ token }}!")
>>> t.render(token="works")
u'Jinja works!'

Reasons/advantages of using a template engine

Work less

Jinja allows us to reuse components (aka common HTML chunks) in many pages and contexts with minor changes. Imagine that we have a footer with some links and contact information, common to all pages in a web application. Using Jinja we can define a separate file named footer.html and we can reuse it with a simple include:


footer.html definition

<footer class="footer">
    <div class=" container-fluid ">
        <span>
            &copy; YourCompany;
        </span>

        <span>
            Contact: bill [ @ ] microsoft.com
        </span>
    </div>
</footer>

footer.html usage in a final page:

<head>
  <title>
    Jinja Template - Cheat Sheet | Dev.to
  </title>
</head>
<body>
    <div class="content">
        Some cool content
    </div>

    <!-- The magic include line --> 
    {% include 'footer.html' %}    

</body>
</html>

Template Inheritance

Inheritance, in Jinja context, means to define a base template that defines the basic structure of all subsequent child templates. This master template can be inherited via extends directive to build variations (new pages).

A real sample

Parent HTML - saved as base.html

<html>
  <head>
    <title>My Jinja {% block title %}{% endblock %} </title>
  </head>
  <body>
    <div class="container">
      <h2>This is from the base template</h2>
      <br>
      { block content }{ endblock }
      <br>
    </div>
  </body>
</html>

The Child template - saved as child.html

{ extends "base.html" }

{ block title } MySample { endblock }

{ block content }
  Cool content here
{ endblock }

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 } becomes MySample
  • { block content } becomes Cool content here

Generated HTML

<html>
  <head>
    <title>My Jinja MySample</title>
  </head>
  <body>
    <div class="container">
      <h2>This is from the base template</h2>
      <br>
      Cool content here
      <br>
    </div>
  </body>
</html>

Jinja - Render Lists

Jinja supports control structures like if/else, for loops to manipulate lists and dictionaries.

List definition

# Define a simple list
users = ['user1','user2', 'user3']

Jinja code snippet

<h1>Members</h1>
<ul>
{% for user in users %}
  <li>{{ user }}</li>
{% endfor %}
</ul>

Generated HTML

<h1>Members</h1>
<ul>
  <li>user1</li>
  <li>user2</li>
  <li>user3</li>
</ul>

For loops can be checked for emptiness with a simple else, as below:

Jinja code snippet

<ul>
{% for user in users %}
    <li>{{ user.username|e }}</li>
{% else %}
    <li><em>no users found</em></li>
{% endfor %}
</ul>

Generated HTML

<h1>Members</h1>
<ul>
  <li>no users found</li>
</ul>

Jinja - HTML Escaping

Escaping is useful when HTML is generated and the injected content might contain >, <, &, or ". Escaping in Jinja works by piping the variable through the |e filter:

Jinja code snippet

{{ content|e }} <!-- content might contain unsafe chars -->

Jinja Filters

Filter sections allow to apply regular Jinja filters on a block of template data - the syntax:

Jinja code snippet

{% filter upper %}
    uppercase me
{% endfilter %}

Generated HTML

UPPERCASE ME

Jinja Math

Jinja allows you to compute values. Here are some samples:

{{ 1 + 1 }} will render 1
{{ 1 / 2 }} will render 0.5
{{ 11 % 7 }} will render 4

If this Jinja Template cheat sheet sounds like something that you can use in your development, we can move forward with a real sample coded on top of Now UI Dashboard, a popular (free) design crafted by Creative-Tim.
Being an open-source project released by AppSeed under the MIT license, the project can be used for unlimited hobby & commercial projects.

Jinja Template - Now UI Sample

The seed project is basically a lightweight Flask project coded without a database or other hard dependencies. The project comes with deployment scripts for Docker, HEROKU, and Gunicorn/Nginx stack.


How to compile Jinja Now UI (information extracted from README file)

$ # Clone the sources
$ git clone https://github.com/app-generator/jinja-template-now-ui-dashboard.git
$ cd jinja-template-now-ui-dashboard
$
$ # Virtualenv set up (Unix based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Install requirements
$ pip3 install -r requirements.txt
$
$ # Set the FLASK_APP environment variable
$ export FLASK_APP=run.py
$
$ # Run the Jinja Template
$ flask run
$
$ # Access the UI in browser: http://127.0.0.1:5000/

If all goes well, we should see Jinja Now UI running on port 5000:

Jinja Template - Now UI Dashboard, the main screen.


Jinja Now UI - Google Maps Page

Jinja Template - Now UI Dashboard, the main screen.


Jinja Now UI - User Profile Page

Jinja Template - Now UI Dashboard, user profile page.


Jinja Now UI - Codebase structure

< PROJECT ROOT >
   |
   |-- app/__init__.py
   |-- app/
   |    |-- static/
   |    |    |-- <css, JS, images>         # CSS files, JS, Img
   |    |
   |    |-- templates/
   |    |    |
   |    |    |-- includes/            # Page chunks, components
   |    |    |    |
   |    |    |    |-- navigation.html # Top bar
   |    |    |    |-- sidebar.html    # Left sidebar
   |    |    |    |-- scripts.html    # COMMON JS scripts 
   |    |    |    |-- footer.html     # The common footer
   |    |    |
   |    |    |-- layouts/             # App Layouts 
   |    |    |    |
   |    |    |    |-- base.html       # Used by common pages
   |    |    |    
   |    |    |
   |    |  index.html                 # The default page
   |    |  login.html                 # Auth Login Page
   |    |  register.html              # Auth Registration Page
   |    |  page-404.html              # Error 404 page 
   |    |  page-500.html              # Error 500 page 
   |    |    *.html                   # All other pages
   |
   |-- requirements.txt
   |
   |-- run.py
   |
   |-- *******************************************

Thanks for reading! Some links to move forward with Jinja

Posted on by:

sm0ke profile

Sm0ke

@sm0ke

#Automation, my favorite programming language

Discussion

markdown guide
 

Jinja is something that I'm using on a daily basis.
Thanks, good content ..