DEV Community

Cover image for Jinja Template - Cheat Sheet and FREE Samples
Sm0ke
Sm0ke

Posted on • Updated on • Originally published at appseed.us

Jinja Template - Cheat Sheet and FREE Samples

Hello Coders,

This article presents a short introduction to Flask/Jinja Template system, a modern and designer-friendly 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. For newcomers, Jinja is a Python library used by popular web frameworks like Flask, FastAPI, and Django to serve HTML pages in a secure and efficient way.

Thanks for reading!


Soft UI Dashboard

Admin dashboard generated by AppSeed in Flask Framework. Designed for those who like bold elements and beautiful websites, Soft UI Dashboard is ready to help you create stunning websites and webapps. Soft UI Dashboard is built with over 70 frontend individual elements, like buttons, inputs, navbars, navtabs, cards or alerts, giving you the freedom of choosing and combining.


Jinja Template - Soft UI Dashboard, open-source Bootstrap 5 design.


Material Design

Material Kit is a Free Bootstrap 5 UI Kit with a fresh, new design inspired by Google's material design. Material Kit makes use of light, surface and movement. It uses a deliberate color choice, edge-to-edge imagery and large scale typography.


Jinja Template - Material Kit Design.


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
Enter fullscreen mode Exit fullscreen mode

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!'
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

The Child template - saved as child.html

{ extends "base.html" }

{ block title } MySample { endblock }

{ block content }
  Cool content here
{ endblock }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

Jinja code snippet

<h1>Members</h1>
<ul>
{% for user in users %}
  <li>{{ user }}</li>
{% endfor %}
</ul>
Enter fullscreen mode Exit fullscreen mode

Generated HTML

<h1>Members</h1>
<ul>
  <li>user1</li>
  <li>user2</li>
  <li>user3</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Generated HTML

<h1>Members</h1>
<ul>
  <li>no users found</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

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 -->
Enter fullscreen mode Exit fullscreen mode

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 %}
Enter fullscreen mode Exit fullscreen mode

Generated HTML

UPPERCASE ME
Enter fullscreen mode Exit fullscreen mode

Jinja Math

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

{{ 1 + 1 }} will render 1
Enter fullscreen mode Exit fullscreen mode
{{ 1 / 2 }} will render 0.5
Enter fullscreen mode Exit fullscreen mode
{{ 11 % 7 }} will render 4
Enter fullscreen mode Exit fullscreen mode

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.


Flask Bootstrap 5

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 Volt (information extracted from README file)

$ # Clone the sources
$ git clone https://github.com/app-generator/jinja-volt-dashboard.git
$ cd jinja-volt-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/
Enter fullscreen mode Exit fullscreen mode

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

Jinja Template - Volt Dashboard, the main screen.


Flask Datta Able

Datta Able is the most stylized Bootstrap 4 Lite Admin Template, around all other Lite/Free admin templates in the market. It comes with high feature-rich pages and components with fully developer-centric code. Comes with error/bug-free, well structured, well-commented code and regularly with all latest updated code. This saves you a large amount of developing backend application time and it is fully customizable



Jinja Datta Able - Open-Source admin dashboard crafted in Jinja.


Flask Pixel UI

Pixel is a free, fully responsive, and modern Bootstrap 4 UI Kit that will help you build creative and professional websites. Use our components and sections, switch some Sass variables to build and arrange pages to best suit your needs.

Pixel Lite comes with 6 premium example pages that we created to show you the beautiful user interfaces that can be created. Some of these pages are a pricing page, about page, contact page, login and register pages.



Jinja Pixel UI - Open-source Jinja template provided by AppSeed.


Gradient Able Flask

Open-source Jinja template coded in Flask Framework. Gradient Able Bootstrap 4 Free/Lite Admin Template is a complete solution for your dashboard creation. Gradient Able stands out from the crowd with an elegant look that combines soft gradient colors with well-suited typography and great cards and graphics.



Jinja Template Gradient Able - Open-Source template project provided by AppSeed.


Thanks for reading! For more resources, please access:


Top comments (2)

Collapse
 
uithemes profile image
ui-themes

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

Collapse
 
sm0ke profile image
Sm0ke

Yw! :)