Welcome! This site is currently in beta. Get 10% off everything with promo code BETA10.

How to Use the Jinja Template Engine

  • Introduction

What is a Flask Template?

It's just html, flask render_template, flexible placeholders, jinja if , else, extends and block, jinja comments, what's next: style points, summary: how to use the jinja template engine, template inheritance faq.

Hopefully, in the last section, you've gotten comfortable with the basics of how to make a Flask app and how to go about making basic routes .

But get ready, because you're about to go from 0 to 60 in this course. You'll be picking up the pace going forward. There won't be full code examples, but there will be code snippets with enough information to guide you through to making a full Flask app. As long as you read carefully, or ask for guidance on Discord or from your mentor, you should be just fine!

How did you do with making your own routes ? Did you try adding some flavor with HTML to make it look more professional? Did your wrists start getting sore reaching for those angle brackets all the time? Seems like a pain, right?

Having to make a brand new HTML string every time you want to make a new route feels very tedious. But here's the great news with Flask: You don't have to do that all the time! This lesson introduces the Jinja2 template engine to make your life easier!

The only job of our view functions should be to generate a response to a request; that's it. Having to also make the pages? What a pain! For that, the creators of Flask also built Jinja , also called Jinja2, which is a Flask template engine.

Flask templates are files that contain the text of a response. Pages that say things like, "Upload your corn flake collection here!" are great, but that's only text.

Templates also support placeholder variables for the dynamic parts of the page, meaning those that change depending on the context of a request (whose corn flake collection, if the corn flakes are gluten-free, etc). These variables get replaced with real values through a process called rendering . And that's what Jinja's job is, to take the values those variables should take on passed in from Flask, then render those values in with the surrounding text. Let's try this thing out!

Making a Jinja2 Template

Before you get started, make a folder named templates , which will live right inside your flask-webdev directory. That's because, by default, Flask looks for your templates in a folder called exactly that: templates . Once you've done that, you're ready to go!

First things first, let's get a simple template rendered. Think of a template as just an HTML file. Make a new template file, templates/index.html . Put in the following:

Now in your hello.py , you'll need to import render_template , then replace your index() function:

With the render_template() function, all you need to do is indicate the path to the template relative to your templates folder, which is simply "index.html" . When a request is received for the index page and render_template() is called, Flask will enlist the help of Jinja2 to render the template.

Let 'er rip! Run the app with flask run and watch as you get the same output. A little boring, huh? Just wait, you're gonna go dynamic .

While a template is pretty much HTML, it's also a little more than that with Jinja. To help demonstrate, let's make another route, this time a dynamic one. Feel free to use one you might have made before in order to complete this next part.

The render_template() has more power than it might look. This function utilizes the well-known Pythonism known as keyword arguments , often seen as **kwargs in the wild. To call the function in the previous user() function example and still get the same effect, you'd do this:

In this example, you indicate which template you want Jinja to render and also pass in our name parameter along to Jinja. The name on the left side of the = is what Jinja will use as the placeholder name inside the template. The other name on the right side is the variable in the function scope.

Now when you load the user.html template, you'll see—whah!? You say you haven't made such a template yet that can handle this passed-in variable? Oh dear, let's take care of that right away!

Using Variables in Jinja Templates

From the last lesson, you know from believing your nomadic Flask course creator and all his sage, vast wisdom (who couldn't quite type the previous with a straight face) that the Jinja template engine can handle variables as long as the Flask application does its part by passing them over. For a simple but dynamic page that does this relay, the view function would look like this:

Crack open a new user.html template file and crack your knuckles 'cause here's the template content:

Wuzzat?! Looks like some weird HTML, but this is how Jinja likes its variables prepared for breakfast. Er, to render. The double curly brackets {{}} tell Jinja that whatever's inside them is a placeholder that should have a value assigned to it, and to render the template with that value instead. If you head to localhost:5000/user/Tom in your browser, you'll be greeted as Tom, even though that's probably not your name!

A screenshot of a browser window with the text 'Hello, Tom!' as the web page content

Here's the really neat thing: you can type almost anything Pythonic in these placeholder sections, and Jinja will know how to render it. Even cooler, you can put these placeholders almost anywhere in the template, and Jinja will still expand them to their actual values. That is, as long as you pass every value Jinja needs to render into the template. Here are some other other examples:

Dictionaries, indexing a list with another variable, changes to styling, even calling object methods. All of it works in a placeholder if it's 1) Python code and 2) Jinja knows about it.

Oh, and one more thing! Jinja also includes filters which can go after a variable with a pipe character in between. For that last example about screaming, you can also do the following to get the same result:

upper is just one filter to choose from, but here are some others:

Filter name Description
Uppercase the first character
Lowercase all characters
Render value without applying escaping
Remove any HTML tags before rendering
Return a titlecased version of the value
Strip leading and trailing characters
Uppercase all characters

You just learned about variables in Jinja, but don't you want more control over your templates? You're in luck because coming up, you'll apply control structures to your templates.

You were just introduced to variables in Jinja and how they put the power of Python into your templates, but there must be more, right? There is, and in this section, you'll get to know the control structures that Jinja provides for you—the if s, the for s, and a few mores!

Control Structures

Python wouldn't be Python without its conditionals and control flow. And it turns out Jinja wouldn't be Jinja for the same reason! Let's just go straight through what control structures Jinja has, and take note that each of these uses a {% ... %} construct:

"Should I display that element, or shouldn't I?" That, along with other hard and not-so-hard questions, can be handled with conditional statements:

Now you can know who's looking at the page! Unless they don't tell us...

Lists of elements are no match for Jinja; they shall be rendered consecutively if you so choose! These are great for using in HTML list tags.

Macros? What the heck are those? Think of them as the Jinja version of Python functions. They're great for avoiding monotonous tasks. Watch:

Automation! The best thing since sliced bread.

To copy others is necessary, but to copy oneself is pathetic. Pablo Picasso

Y'know, Picasso is onto something here. In some cases, it's extremely useful to copy one template into another, and that's exactly what Jinja's import statement does. But, "to copy oneself is pathetic?" If he's talking about Jinja, I think maybe he meant "silly."

Would some macro statements and an import or two be useful? You betcha. In fact, that's the definition of "synergy":

Defining one or more macros and one template, then importing them for painless access in another? Sweet.

Are you a Java(Script) coder? 'Cause the extends keyword makes a comeback in Jinja (if you can call it that). You're darn tootin': inheritance in templates! Using block structures, you can define and then extend or even override blocks of template code.

If you make a "base" template called base.html , you can "reserve" blocks of code to hold certain content in certain places that can be inherited later.

You'll see here that blocks of code are defined with arbitrary names, in this case, head , title , and body . Another template that extends this base template (let's call it index.html ) might look like this:

It has an extends control structure, which means it's definitely a derived template. Alrighty, try to follow along here: so you see how the title block is inside the head block in base.html ? It is outside the head block in index.html . For blocks that show up in both base and derived templates, the content in the derived template always gets used instead of the content in the base template. Here's how index.html is rendered:

  • title - content is Home
  • head - the textual content is Home - My App since title is contained within head , and shows up as the page's title (the browser tab text); super() is used to bring in the content from the base class, then afterwards it is extended with a <style> tag
  • body - content is just Hello World!

A screenshot of a webpage demonstrating how the structure of the page has been extended from a base template

These don't actually control anything, but they can be useful! Instead of using <!-- HTML comments --> for templates, it's better to use {# these comments #} , mainly because the Jinja comments won't get included in the final HTML, whereas HTML comments will get sent to the client and visible to anyone who opens the inspector.

Phew! Those are all the important control structure you'll need to be familiar with in this course. Don't worry, you'll see them again and again so you'll get used to them.

But gosh, does any of this make you feel a little uneasy? Now don't get me wrong, Flask is freakin' cool, but these pages look like they came from the Internet Stone Age, back when dial-up was a thing. And to answer the next question you almost certainly have: YES! Of course, there's an easy way to get a much prettier, modern look! Continue on with the next lessons for some serious style.

You've now dipped your toes into creating more sophisticated applications with Flask, and it looks like you're picking up steam! In this lesson, you've:

  • Discovered that templates are your best friends for avoiding repetition and that you can use the Jinja template engine to render responses dynamically.
  • Set up a templates folder and learned how to render simple HTML templates using render_template() .
  • Understood how to pass variables to templates in Flask, enabling dynamic content to be displayed to the user, such as personalized greetings.
  • Played with dynamic placeholders in templates, learning that you can essentially run Python code in your HTML using Jinja syntax.
  • Grasped control structures in Jinja, like if , elif , else , for , and import , which allow you to add conditional logic and loops to your templates.
  • Tackled template inheritance with the extends and block keywords.
  • Touched on macros and import in Jinja, which act like functions in Python and can be reused across different templates.

Inheritance can be tricky to wrap your head around, so here is an FAQ of common questions students have.

Here are questions that have come up from students and may come up for you. :)

Q: I inherited from bootstrap base template in template A, but when rendering template A, nothing shows up. What's wrong?

This could be because you didn't place down any block s in your inherited template. Flask-Bootstrap has pre-defined block s that are "copied" over when you use extends . Plain HTML gets overridden.

If you did place down block s, you may not have used {{ super() }} inside of it, which would override anything you defined in that block in the base template.

Q: What is the difference between <head> & <header> ?

Here's a helpful Stackoverflow post that clarifies: What is the real difference between the "head" and "header" tag?

Q: Some parts of my HTML show up twice when using blocks

This happens sometimes because you place down a parent block along with a child block inside it in the inherited template. Usually, it is enough to just place down the child block only and add the additional HTML you want to it.

Template inheritance allows you to "say a lot with just a little," meaning it gives you the capability to plop in chunks of HTML with only a couple lines of Jinja code. Within inherited templates, placing down fewer block s already pre-defined in your base template is usually better. So when in doubt, try using a subset of block s from your base template.

Q: I don't know where to start. How do I know the base template is doing what I need it to?

Let's assume you are starting with a good amount of HTML code without any Jinja. There are probably multiple HTML files that have a lot of similarities. The idea of creating a base template is to capture these similarities while still allowing for child templates to have their own content. On somewhat rare occasions, a child template may "overwrite" some parts of the HTML structure. Another nice thing about having a base template is that changes to the base template are carried over to the child templates, which saves oodles of time on the frontend so you can focus on making the backend solid.

If you're stuck, the following is a good workflow. The basis of it is to start with a bunch of already written HTML code and strip it down to the parts that are common to all templates.

First, make two copies of the index template. Name one copy as base.html and the other as index2.html . For now you'll focus on the base.html template, and you'll come back to index2.html a few steps afterward.

  • The index template is often the simplest template of the bunch, so it is easiest to start with

Create a couple of temporary routes for displaying this base template. It can be as simple as

In base.html , define block s based on the structural parts of a page. Blocks make your templates extensible and flexible, otherwise you'd have to rewrite HTML for entire pages.

a. Start with head and body to start. The head block will be defined right inside the <head> tag, which in turn contains the title, links to stylesheets and scripts, and other metadata. The body is what your users will see. Example:

b. After that, define the nested blocks, like title inside the head block and header inside the body block:

Starting to see the pattern?

c. Continue onto the next layer of nested blocks. After defining blocks for this layer, you probably have enough blocks for a decent start to a base template! Any deeper than 4 nested blocks starts to become to much. Keep in mind you don't need a block for every HTML tag; just a handful of blocks will do.

Launch your app and take a look at how your base.html template looks. Does it still look like your index page? If something doesn't look right, go back to step 3 adjust your blocks until things look the same.

From your base.html template, delete any content that is exclusive to the index page, but keep the parts that will probably be on almost every page. Things like "Welcome to my site!" would be exclusive to the index page. Things like the header and navigation bar will likely be shown on just about every page. If you're not sure if something should stay or go, err on the side of keeping it. After this, you've created the first draft of your base template!

Now you're ready to pull up index2.html . If you're using an IDE that supports side-by-side tabs like VSCode, pull up the original index.html alongside it. In index2.html , delete the existing HTML code and try to reconstruct the index page by extending index2.html from base.html and using the blocks defined within base.html . In other words, use template inheritance to re-make the index page. Remember you can check the /index2 route you made in step 2 to see how it compares to /index .

  • Most of the time, you won't need to change the HTML inside an inherited block, but if you do, you can redeclare it in a derived template and change or add anything you need to the block.

Q: I added Flask Bootstrap to my project, and now the blocks in my existing templates are screwed up when rendered. How can I fix it?

When you initialize Flask-Bootstrap in your project and inherit a template from bootstrap/base.html , it will define some blocks already, which you can see here . If you have any of these blocks in your templates, keep in mind where you do or don't have {{ super() }} .

Don't be intimidated by Flask-Bootstrap! You can actually see what Flask-Bootstrap has defined in its bootstrap/base.html template here . It's only 34 lines and might be simpler than you think.

Jinja2 template syntax #

So far, only variable substitution has been used in Jinja2 template examples. This is the simplest and most understandable example of using templates. Syntax of Jinja templates is not limited to this.

In Jinja2 templates you can use :

conditions (if/else)

loops (for)

filters - special built-in methods that allow to convert variables

tests - are used to check whether a variable matches a condition

In addition, Jinja supports inheritance between templates and also allows adding the contents of one template to another. This section covers only few possibilities. More information about Jinja2 templates can be found in documentation .

All files used as examples in this subsection are in 3_template_syntax/ directory

Script cfg_gen.py will be used to generate templates.

In order to see the result, you have to call the script and give it two arguments:

file with variables in YAML format

The result will be displayed on standard output stream.

Example of script run:

Parameters trim_blocks and lstrip_blocks are described in the following subsection.

Jinja2 Set Variable Block

Jinja2: Using Set Variable Block

Abstract: This article explores the usage of the set variable block in Jinja2 templates. Learn how to assign and modify values using this feature.

Jinja2 is a powerful templating language for Python that enables developers to create dynamic and reusable web page layouts. One of the key features of Jinja2 is the ability to set and manipulate variables within templates. In this article, we will explore the use of the {% set %} block in Jinja2 and how it can be used to simplify template logic and improve code readability.

What is the Set Variable Block?

The {% set %} block is a feature in Jinja2 that allows you to set and manipulate variables within a template. This block can be used to store values, perform calculations, and simplify template logic. The syntax for the {% set %} block is as follows:

Where variable_name is the name of the variable you want to set, and value is the value you want to assign to the variable. The value can be a string, number, list, dictionary, or any other Python data type.

Using the Set Variable Block

The {% set %} block can be used in a variety of ways to simplify template logic and improve code readability. Here are some examples:

Storing Values

The most basic use of the {% set %} block is to store values that will be used later in the template. For example:

{{ greeting }}

Performing Calculations

The {% set %} block can also be used to perform calculations within a template. For example:

The sum is: {{ sum }}

Simplifying Template Logic

The {% set %} block can also be used to simplify template logic by storing complex expressions or calculations in a variable. For example:

The total price is: {{ total }}

Best Practices

When using the {% set %} block in Jinja2, there are a few best practices to keep in mind:

  • Use descriptive variable names to improve code readability.
  • Avoid setting variables within loops or conditionals, as this can make the code harder to read and debug.
  • Use the {% with %} block instead of {% set %} for complex expressions or calculations, as it can improve code readability and reduce repetition.

The {% set %} block is a powerful feature in Jinja2 that enables developers to set and manipulate variables within templates. By using this block, you can simplify template logic, improve code readability, and reduce repetition. When using the {% set %} block, be sure to follow best practices to ensure that your code is maintainable and easy to read.

  • Jinja2 Documentation: Set Block
  • A Primer on Jinja Templating
  • Jinja2 Documentation

Message Handling in Dialogs: Using DialogMainForm and Checks prior to TranslateMessage and DispatchMessage

This article discusses the process of handling messages in dialogs using DialogMainForm and checks prior to TranslateMessage and DispatchMessage in C++.

Tags: :  Jinja2 Templates Python SET_VAR

Latest news

  • Making Simple Polygon Coordinates SF-friendly
  • Handling Background Notifications in iOS with React Native and Firebase
  • RestClientSingleton: Managing Instances in Documentation
  • Opening PDF Files via VBA in Excel: Troubleshooting Common Issues
  • Vue Router: Redirecting Within a Component to Different Routes
  • GitLab: Unknown Keys in YAML config for secrets and triggers in myJob
  • React.js & Rxjs: Subscribing Inside Store File for a 'Bomb' Element in a Game of Life Implementation
  • Error: Survey.Model not constructor
  • Applying Event Listeners to New Elements in Jupyter Notebook-like Input
  • Enabling Efficiency Mode (EcoQoS) for a Specific Process ID in C++
  • Converting Flat File JSON Structure using ADF: Transforming Data
  • LLDB Debugger Not Working in VSCode Despite Shifting from Clion to Clang
  • Resolving 404 Error in Angular.json for Browser Application
  • Adding Git Dependency for a Python Package in Bazel
  • Handle Entire Cycle Scrapy Spider Runs with async function in Twisted
  • TensorFlowLite Model Compatibility Issues with oneDNN Custom Operations: Python Error
  • Downloading Real-Time RTMP Data with Java for Livestream Recordings
  • Automatically Deleting User Data in Discord.py: Is It Possible?
  • Handling Complex API Queries with Multiple Parameters in SpringBoot/JPA
  • Resolving 'argumentTypeMismatch: Text can't be assigned to parameter type String' Error in Flutter
  • Fixing Unity Hub (3.8.0) Refusing to Open on macOS Catalina
  • Statement: return False using not? In Python Hangman Game Practice
  • Upgrading TensorFlow Code: From CorefModel (1.14) to New Library
  • Adding Contour Line Labels to DEM using GDAL 3.6.2
  • Implementing Custom Markers in Apple Maps: A Beginner's Guide
  • Unable to Log in as mysql root user with Laravel Sail
  • Error: Current Transaction Aborted - SQL Commands Ignored
  • Docker: Unable to Find tini - Troubleshooting Steps
  • Java Service: JAX-RS Returning XML or JSON Response based on URL Extension
  • Activating Microsoft Purview Service Encryption Customer Key with Key Vault Firewall
  • Importing and Analyzing Big XML Files: Correlation Between Events in R
  • Custom Hibernate Validator Class-Level Message Configuration
  • Measuring Doubling Transactions in Power BI: A Step-by-Step Guide
  • Removing a Widget: Screen, RecycleView, and Kivy Card
  • Creating Flexible-Width HTML Tables for Software Development
  • Jinja Documentation (2.10.x) »

Warning: This is an old version. The latest stable version is Version 3.0.x .

Template Designer Documentation ¶

This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Jinja templates. As the template engine is very flexible, the configuration from the application can be slightly different from the code presented here in terms of delimiters and behavior of undefined values.

A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn’t need to have a specific extension: .html , .xml , or any other extension is just fine.

A template contains variables and/or expressions , which get replaced with values when a template is rendered ; and tags , which control the logic of the template. The template syntax is heavily inspired by Django and Python.

Below is a minimal template that illustrates a few basics using the default Jinja configuration. We will cover the details later in this document:

The following example shows the default configuration settings. An application developer can change the syntax configuration from {% foo %} to <% foo %> , or something similar.

There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:

{% ... %} for Statements

{{ ... }} for Expressions to print to the template output

{# ... #} for Comments not included in the template output

#   ... ## for Line Statements

Variables ¶

Template variables are defined by the context dictionary passed to the template.

You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable.

You can use a dot ( . ) to access attributes of a variable in addition to the standard Python __getitem__ “subscript” syntax ( [] ).

The following lines do the same thing:

It’s important to know that the outer double-curly braces are not part of the variable, but the print statement. If you access variables inside tags don’t put the braces around them.

If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated over, and to fail for every other operation.

Implementation

For the sake of convenience, foo.bar in Jinja2 does the following things on the Python layer:

check for an attribute called bar on foo ( getattr(foo, 'bar') )

if there is not, check for an item 'bar' in foo ( foo.__getitem__('bar') )

if there is not, return an undefined object.

foo['bar'] works mostly the same with a small difference in sequence:

check for an item 'bar' in foo . ( foo.__getitem__('bar') )

if there is not, check for an attribute called bar on foo . ( getattr(foo, 'bar') )

This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks up attributes.

Variables can be modified by 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.

For example, {{ name|striptags|title }} will remove all HTML Tags from variable name and title-case the output ( title(striptags(name)) ).

Filters that accept arguments have parentheses around the arguments, just like a function call. For example: {{ listx|join(', ') }} will join a list with commas ( str.join(', ', listx) ).

The List of Builtin Filters below describes all the builtin filters.

Beside filters, there are also so-called “tests” available. Tests can be used to test a variable against a common expression. To test a variable or expression, you add is plus the name of the test after the variable. For example, to find out if a variable is defined, you can do name is defined , which will then return true or false depending on whether name is defined in the current template context.

Tests can accept arguments, too. If the test only takes one argument, you can leave out the parentheses. For example, the following two expressions do the same thing:

The List of Builtin Tests below describes all the builtin tests.

To comment-out part of a line in a template, use the comment syntax which is by default set to {# ... #} . This is useful to comment out parts of the template for debugging or to add information for other template designers or yourself:

Whitespace Control ¶

In the default configuration:

a single trailing newline is stripped if present

other whitespace (spaces, tabs, newlines etc.) is returned unchanged

If an application configures Jinja to trim_blocks , the first newline after a template tag is removed automatically (like in PHP). The lstrip_blocks option can also be set to strip tabs and spaces from the beginning of a line to the start of a block. (Nothing will be stripped if there are other characters before the start of the block.)

With both trim_blocks and lstrip_blocks enabled, you can put block tags on their own lines, and the entire block line will be removed when rendered, preserving the whitespace of the contents. For example, without the trim_blocks and lstrip_blocks options, this template:

gets rendered with blank lines inside the div:

But with both trim_blocks and lstrip_blocks enabled, the template block lines are removed and other whitespace is preserved:

You can manually disable the lstrip_blocks behavior by putting a plus sign ( + ) at the start of a block:

You can also strip whitespace in templates by hand. If you add a minus sign ( - ) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed:

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9 , the output would be 123456789 .

If Line Statements are enabled, they strip leading whitespace automatically up to the beginning of the line.

By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline .

You must not add whitespace between the tag and the minus sign.

It is sometimes desirable – even necessary – to have Jinja ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you have to use a trick.

The easiest way to output a literal variable delimiter ( {{ ) is by using a variable expression:

For bigger sections, it makes sense to mark a block raw . For example, to include example Jinja syntax in a template, you can use this snippet:

Line Statements ¶

If line statements are enabled by the application, it’s possible to mark a line as a statement. For example, if the line statement prefix is configured to # , the following two examples are equivalent:

The line statement prefix can appear anywhere on the line as long as no text precedes it. For better readability, statements that start a block (such as for , if , elif etc.) may end with a colon:

Line statements can span multiple lines if there are open parentheses, braces or brackets:

Since Jinja 2.2, line-based comments are available as well. For example, if the line-comment prefix is configured to be ## , everything from ## to the end of the line is ignored (excluding the newline sign):

Template Inheritance ¶

The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.

Sounds complicated but is very basic. It’s easiest to understand it by starting with an example.

Base Template ¶

This template, which we’ll call base.html , defines a simple HTML skeleton document that you might use for a simple two-column page. It’s the job of “child” templates to fill the empty blocks with content:

In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those placeholders in the template.

Child Template ¶

A child template might look like this:

The {% extends %} tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, it first locates the parent. The extends tag should be the first tag in the template. Everything before it is printed out normally and may cause confusion. For details about this behavior and how to take advantage of it, see Null-Master Fallback . Also a block will always be filled in regardless of whether the surrounding condition is evaluated to be true or false.

The filename of the template depends on the template loader. For example, the FileSystemLoader allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash:

But this behavior can depend on the application embedding Jinja. Note that since the child template doesn’t define the footer block, the value from the parent template is used instead.

You can’t define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in “both” directions. That is, a block tag doesn’t just provide a placeholder to fill - it also defines the content that fills the placeholder in the parent . If there were two similarly-named {% block %} tags in a template, that template’s parent wouldn’t know which one of the blocks’ content to use.

If you want to print a block multiple times, you can, however, use the special self variable and call the block with that name:

Super Blocks ¶

It’s possible to render the contents of the parent block by calling super . This gives back the results of the parent block:

Named Block End-Tags ¶

Jinja2 allows you to put the name of the block after the end tag for better readability:

However, the name after the endblock word must match the block name.

Block Nesting and Scope ¶

Blocks can be nested for more complex layouts. However, per default blocks may not access variables from outer scopes:

This example would output empty <li> items because item is unavailable inside the block. The reason for this is that if the block is replaced by a child template, a variable would appear that was not defined in the block or passed to the context.

Starting with Jinja 2.2, you can explicitly specify that variables are available in a block by setting the block to “scoped” by adding the scoped modifier to a block declaration:

When overriding a block, the scoped modifier does not have to be provided.

Template Objects ¶

Changed in version 2.4.

If a template object was passed in the template context, you can extend from that object as well. Assuming the calling code passes a layout template as layout_template to the environment, this code works:

Previously, the layout_template variable had to be a string with the layout template’s filename for this to work.

HTML Escaping ¶

When generating HTML from templates, there’s always a risk that a variable will include characters that affect the resulting HTML. There are two approaches:

manually escaping each variable; or

automatically escaping everything by default.

Jinja supports both. What is used depends on the application configuration. The default configuration is no automatic escaping; for various reasons:

Escaping everything except for safe values will also mean that Jinja is escaping variables known to not include HTML (e.g. numbers, booleans) which can be a huge performance hit.

The information about the safety of a variable is very fragile. It could happen that by coercing safe and unsafe values, the return value is double-escaped HTML.

Working with Manual Escaping ¶

If manual escaping is enabled, it’s your responsibility to escape variables if needed. What to escape? If you have a variable that may include any of the following chars ( > , < , & , or " ) you SHOULD escape it unless the variable contains well-formed and trusted HTML. Escaping works by piping the variable through the |e filter:

Working with Automatic Escaping ¶

When automatic escaping is enabled, everything is escaped by default except for values explicitly marked as safe. Variables and expressions can be marked as safe either in:

the context dictionary by the application with markupsafe.Markup , or

the template, with the |safe filter

The main problem with this approach is that Python itself doesn’t have the concept of tainted values; so whether a value is safe or unsafe can get lost.

If a value is not marked safe, auto-escaping will take place; which means that you could end up with double-escaped contents. Double-escaping is easy to avoid, however: just rely on the tools Jinja2 provides and don’t use builtin Python constructs such as str.format or the string modulo operator (%) .

Jinja2 functions (macros, super , self.BLOCKNAME ) always return template data that is marked as safe.

String literals in templates with automatic escaping are considered unsafe because native Python strings ( str , unicode , basestring ) are not markupsafe.Markup strings with an __html__ attribute.

List of Control Structures ¶

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. With the default syntax, control structures appear inside {% ... %} blocks.

Loop over each item in a sequence. For example, to display a list of users provided in a variable called users :

As variables in templates retain their object properties, it is possible to iterate over containers like dict :

Note, however, that Python dicts are not ordered ; so you might want to either pass a sorted list of tuple s – or a collections.OrderedDict – to the template, or use the dictsort filter.

Inside of a for-loop block, you can access some special variables:

Variable

Description

The current iteration of the loop. (1 indexed)

The current iteration of the loop. (0 indexed)

The number of iterations from the end of the loop (1 indexed)

The number of iterations from the end of the loop (0 indexed)

True if first iteration.

True if last iteration.

The number of items in the sequence.

A helper function to cycle between a list of sequences. See the explanation below.

Indicates how deep in a recursive loop the rendering currently is. Starts at level 1

Indicates how deep in a recursive loop the rendering currently is. Starts at level 0

The item from the previous iteration of the loop. Undefined during the first iteration.

The item from the following iteration of the loop. Undefined during the last iteration.

True if previously called with a different value (or not called at all).

Within a for-loop, it’s possible to cycle among a list of strings/variables each time through the loop by using the special loop.cycle helper:

Since Jinja 2.1, an extra cycle helper exists that allows loop-unbound cycling. For more information, have a look at the List of Global Functions .

Unlike in Python, it’s not possible to break or continue in a loop. You can, however, filter the sequence during iteration, which allows you to skip items. The following example skips all the users which are hidden:

The advantage is that the special loop variable will count correctly; thus not counting the users not iterated over.

If no iteration took place because the sequence was empty or the filtering removed all the items from the sequence, you can render a default block by using else :

Note that, in Python, else blocks are executed whenever the corresponding loop did not break . Since Jinja loops cannot break anyway, a slightly different behavior of the else keyword was chosen.

It is also possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps or RDFa. To use loops recursively, you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.

The following example implements a sitemap with recursive loops:

The loop variable always refers to the closest (innermost) loop. If we have more than one level of loops, we can rebind the variable loop by writing {% set outer_loop = loop %} after the loop that we want to use recursively. Then, we can call it using {{ outer_loop(…) }}

Please note that assignments in loops will be cleared at the end of the iteration and cannot outlive the loop scope. Older versions of Jinja2 had a bug where in some circumstances it appeared that assignments would work. This is not supported. See Assignments for more information about how to deal with this.

If all you want to do is check whether some value has changed since the last iteration or will change in the next iteration, you can use previtem and nextitem :

If you only care whether the value changed at all, using changed is even easier:

The if statement in Jinja is comparable with the Python if statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false:

For multiple branches, elif and else can be used like in Python. You can use more complex Expressions there, too:

If can also be used as an inline expression and for loop filtering .

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).

Here’s a small example of a macro that renders a form element:

The macro can then be called like a function in the namespace:

If the macro was defined in a different template, you have to import it first.

Inside macros, you have access to three special variables:

If more positional arguments are passed to the macro than accepted by the macro, they end up in the special varargs variable as a list of values.

Like varargs but for keyword arguments. All unconsumed keyword arguments are stored in this special variable.

If the macro was called from a call tag, the caller is stored in this variable as a callable macro.

Macros also expose some of their internal details. The following attributes are available on a macro object:

The name of the macro. {{ input.name }} will print input .

A tuple of the names of arguments the macro accepts.

A tuple of default values.

This is true if the macro accepts extra keyword arguments (i.e.: accesses the special kwargs variable).

This is true if the macro accepts extra positional arguments (i.e.: accesses the special varargs variable).

This is true if the macro accesses the special caller variable and may be called from a call tag.

If a macro name starts with an underscore, it’s not exported and can’t be imported.

In some cases it can be useful to pass a macro to another macro. For this purpose, you can use the special call block. The following example shows a macro that takes advantage of the call functionality and how it can be used:

It’s also possible to pass arguments back to the call block. This makes it useful as a replacement for loops. Generally speaking, a call block works exactly like a macro without a name.

Here’s an example of how a call block can be used with arguments:

Filter sections allow you to apply regular Jinja2 filters on a block of template data. Just wrap the code in the special filter section:

Assignments ¶

Inside code blocks, you can also assign values to variables. Assignments at top level (outside of blocks, macros or loops) are exported from the template like top level macros and can be imported by other templates.

Assignments use the set tag and can have multiple targets:

Scoping Behavior

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:

It is not possible with Jinja syntax to do this. Instead use alternative constructs like the loop else block or the special loop variable:

As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes:

Note hat the obj.attr notation in the set tag is only allowed for namespace objects; attempting to assign an attribute on any other object will raise an exception.

New in version 2.10: Added support for namespace objects

Block Assignments ¶

New in version 2.8.

Starting with Jinja 2.8, it’s possible to also use block assignments to capture the contents of a block into a variable name. This can be useful in some situations as an alternative for macros. In that case, instead of using an equals sign and a value, you just write the variable name and then everything until {% endset %} is captured.

The navigation variable then contains the navigation HTML source.

Changed in version 2.10.

Starting with Jinja 2.10, the block assignment supports filters.

The extends tag can be used to extend one template from another. You can have multiple extends tags in a file, but only one of them may be executed at a time.

See the section about Template Inheritance above.

Blocks are used for inheritance and act as both placeholders and replacements at the same time. They are documented in detail in the Template Inheritance section.

The include statement is useful to include a template and return the rendered contents of that file into the current namespace:

Included templates have access to the variables of the active context by default. For more details about context behavior of imports and includes, see Import Context Behavior .

From Jinja 2.2 onwards, you can mark an include with ignore missing ; in which case Jinja will ignore the statement if the template to be included does not exist. When combined with with or without context , it must be placed before the context visibility statement. Here are some valid examples:

New in version 2.2.

You can also provide a list of templates that are checked for existence before inclusion. The first template that exists will be included. If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise it will raise an exception.

Changed in version 2.4: If a template object was passed to the template context, you can include that object using include .

Jinja2 supports putting often used code into macros. These macros can go into different templates and get imported from there. This works similarly to the import statements in Python. It’s important to know that imports are cached and imported templates don’t have access to the current template variables, just the globals by default. For more details about context behavior of imports and includes, see Import Context Behavior .

There are two ways to import templates. You can import a complete template into a variable or request specific macros / exported variables from it.

Imagine we have a helper module that renders forms (called forms.html ):

The easiest and most flexible way to access a template’s variables and macros is to import the whole template module into a variable. That way, you can access the attributes:

Alternatively, you can import specific names from a template into the current namespace:

Macros and variables starting with one or more underscores are private and cannot be imported.

Changed in version 2.4: If a template object was passed to the template context, you can import from that object.

Import Context Behavior ¶

By default, included templates are passed the current context and imported templates are not. The reason for this is that imports, unlike includes, are cached; as imports are often used just as a module that holds macros.

This behavior can be changed explicitly: by adding with context or without context to the import/include directive, the current context can be passed to the template and caching is disabled automatically.

Here are two examples:

In Jinja 2.0, the context that was passed to the included template did not include variables defined in the template. As a matter of fact, this did not work:

The included template render_box.html is not able to access box in Jinja 2.0. As of Jinja 2.1, render_box.html is able to do so.

Expressions ¶

Jinja allows basic expressions everywhere. These work very similarly to regular Python; even if you’re not working with Python you should feel comfortable with it.

The simplest form of expressions are literals. Literals are representations for Python objects such as strings and numbers. The following literals exist:

Everything between two double or single quotes is a string. They are useful whenever you need a string in the template (e.g. as arguments to function calls and filters, or just to extend or include a template).

Integers and floating point numbers are created by just writing the number down. If a dot is present, the number is a float, otherwise an integer. Keep in mind that, in Python, 42 and 42.0 are different ( int and float , respectively).

Everything between two brackets is a list. Lists are useful for storing sequential data to be iterated over. For example, you can easily create a list of links using lists and tuples for (and with) a for loop:

Tuples are like lists that cannot be modified (“immutable”). If a tuple only has one item, it must be followed by a comma ( ('1-tuple',) ). Tuples are usually used to represent items of two or more elements. See the list example above for more details.

A dict in Python is a structure that combines keys and values. Keys must be unique and always have exactly one value. Dicts are rarely used in templates; they are useful in some rare cases such as the xmlattr() filter.

true is always true and false is always false.

The special constants true , false , and none are indeed lowercase. Because that caused confusion in the past, ( True used to expand to an undefined variable that was considered false), all three can now also be written in title case ( True , False , and None ). However, for consistency, (all Jinja identifiers are lowercase) you should use the lowercase versions.

Jinja allows you to calculate with values. This is rarely useful in templates but exists for completeness’ sake. The following operators are supported:

Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way. This, however, is not the preferred way to concatenate strings! For string concatenation, have a look-see at the ~ operator. {{ 1 + 1 }} is 2 .

Subtract the second number from the first one. {{ 3 - 2 }} is 1 .

Divide two numbers. The return value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }} .

Divide two numbers and return the truncated integer result. {{ 20 // 7 }} is 2 .

Calculate the remainder of an integer division. {{ 11 % 7 }} is 4 .

Multiply the left operand with the right one. {{ 2 * 2 }} would return 4 . This can also be used to repeat a string multiple times. {{ '=' * 80 }} would print a bar of 80 equal signs.

Raise the left operand to the power of the right operand. {{ 2**3 }} would return 8 .

Comparisons ¶

Compares two objects for equality.

Compares two objects for inequality.

true if the left hand side is greater than the right hand side.

true if the left hand side is greater or equal to the right hand side.

true if the left hand side is lower than the right hand side.

true if the left hand side is lower or equal to the right hand side.

For if statements, for filtering, and if expressions, it can be useful to combine multiple expressions:

Return true if the left and the right operand are true.

Return true if the left or the right operand are true.

negate a statement (see below).

group an expression.

The is and in operators support negation using an infix notation, too: foo is not bar and foo not in bar instead of not foo is bar and not foo in bar . All other expressions require a prefix notation: not (foo and bar).

Other Operators ¶

The following operators are very useful but don’t fit into any of the other two categories:

Perform a sequence / mapping containment test. Returns true if the left operand is contained in the right. {{ 1 in [1, 2, 3] }} would, for example, return true.

Performs a test .

Applies a filter .

Converts all operands into strings and concatenates them.

{{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John' ) Hello John! .

Call a callable: {{ post.render() }} . Inside of the parentheses you can use positional arguments and keyword arguments like in Python:

{{ post.render(user, full=true) }} .

Get an attribute of an object. (See Variables )

If Expression ¶

It is also possible to use inline if expressions. These are useful in some situations. For example, you can use this to extend from one template if a variable is defined, otherwise from the default layout template:

The general syntax is <do something> if <something is true> else <do something else> .

The else part is optional. If not provided, the else block implicitly evaluates into an undefined object:

Python Methods ¶

You can also use any of the methods of defined on a variable’s type. The value returned from the method invocation is used as the value of the expression. Here is an example that uses methods defined on strings (where page.title is a string):

This also works for methods on user-defined types. For example, if variable f of type Foo has a method bar defined on it, you can do the following:

List of Builtin Filters ¶

Return the absolute value of the argument.

Get an attribute of an object. foo|attr("bar") works like foo.bar just that always an attribute is returned and items are not looked up.

See Notes on subscriptions for more details.

A filter that batches items. It works pretty much like slice just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:

Capitalize a value. The first character will be uppercase, all others lowercase.

Centers the value in a field of a given width.

If the value is undefined it will return the passed default value, otherwise the value of the variable:

This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not defined' . If you want to use default with variables that evaluate to false you have to set the second parameter to true :

Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value:

Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.

Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to True the binary prefixes are used (Mebi, Gibi).

Return the first item of a sequence.

Convert the value into a floating point number. If the conversion doesn’t work it will return 0.0 . You can override this default using the first parameter.

Enforce HTML escaping. This will probably double escape variables.

Apply python string formatting on an object:

Group a sequence of objects by a common attribute.

If you for example have a list of dicts or objects that represent persons with gender , first_name and last_name attributes and you want to group all users by genders you can do something like the following snippet:

Additionally it’s possible to use tuple unpacking for the grouper and list:

As you can see the item we’re grouping by is stored in the grouper attribute and the list contains all the objects that have this grouper in common.

Changed in version 2.6: It’s now possible to use dotted notation to group by the child attribute of another attribute.

Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default.

width – Number of spaces to indent by.

first – Don’t skip indenting the first line.

blank – Don’t skip indenting empty lines.

Changed in version 2.10: Blank lines are not indented by default.

Rename the indentfirst argument to first .

Convert the value into an integer. If the conversion doesn’t work it will return 0 . You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as 0b, 0o and 0x for bases 2, 8 and 16 respectively. The base is ignored for decimal numbers and non-string values.

Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter:

It is also possible to join certain attributes of an object:

New in version 2.6: The attribute parameter was added.

Return the last item of a sequence.

Return the number of items in a container.

Convert the value into a list. If it was a string the returned list will be a list of characters.

Convert a value to lowercase.

Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.

The basic usage is mapping on an attribute. Imagine you have a list of users but you are only interested in a list of usernames:

Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:

New in version 2.7.

Return the largest item from the sequence.

case_sensitive – Treat upper and lower case strings as distinct.

attribute – Get the object with the max value of this attribute.

Return the smallest item from the sequence.

Pretty print a variable. Useful for debugging.

With Jinja 1.2 onwards you can pass it a parameter. If this parameter is truthy the output will be more verbose (this requires pretty )

Return a random item from the sequence.

Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.

If no test is specified, each object will be evaluated as a boolean.

Example usage:

Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.

If no test is specified, the attribute’s value will be evaluated as a boolean.

Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument count is given, only the first count occurrences are replaced:

Reverse the object or return an iterator that iterates over it the other way round.

Round the number to a given precision. The first parameter specifies the precision (default is 0 ), the second the rounding method:

'common' rounds either up or down

'ceil' always rounds up

'floor' always rounds down

If you don’t specify a method 'common' is used.

Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through int :

Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.

Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.

Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.

Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:

If you pass it a second argument it’s used to fill missing values on the last iteration.

Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting.

If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default.

It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the attribute parameter:

Changed in version 2.6: The attribute parameter was added.

Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.

Strip SGML/XML tags and replace adjacent whitespace by one space.

Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.

It is also possible to sum up only certain attributes:

Changed in version 2.6: The attribute parameter was added to allow suming up over attributes. Also the start parameter was moved on to the right.

Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.

Dumps a structure to JSON so that it’s safe to use in <script> tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the |tojson filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outside of <script> tags.

The following characters are escaped in strings:

This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition.

The indent parameter can be used to enable pretty printing. Set it to the number of spaces that the structures should be indented with.

Note that this filter is for use in HTML contexts only.

New in version 2.9.

Strip leading and trailing whitespace.

Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255 . If the second parameter is true the filter will cut the text at length. Otherwise it will discard the last word. If the text was in fact truncated it will append an ellipsis sign ( "..." ). If you want a different ellipsis sign than "..." you can specify it using the third parameter. Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.

The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally.

Returns a list of unique items from the the given iterable.

The unique items are yielded in the same order as their first occurrence in the iterable passed to the filter.

attribute – Filter objects with unique values for this attribute.

Convert a value to uppercase.

Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.

Converts URLs in plain text into clickable links.

If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls “nofollow”:

If target is specified, the target attribute will be added to the <a> tag:

Changed in version 2.8+: The target parameter was added.

Count the words in that string.

Return a copy of the string passed to the filter wrapped after 79 characters. You can override this default using the first parameter. If you set the second parameter to false Jinja will not split words apart if they are longer than width . By default, the newlines will be the default newlines for the environment, but this can be changed using the wrapstring keyword argument.

New in version 2.7: Added support for the wrapstring parameter.

Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined are automatically escaped:

Results in something like this:

As you can see it automatically prepends a space in front of the item if the filter returned something unless the second parameter is false.

List of Builtin Tests ¶

Return whether the object is callable (i.e., some kind of function).

Note that classes are callable, as are instances of classes with a __call__() method.

Return true if the variable is defined:

See the default() filter for a simple way to set undefined variables.

Check if a variable is divisible by a number.

Same as a == b.

== , equalto

Check if the value is escaped.

Return true if the variable is even.

Same as a >= b.

Same as a > b.

> , greaterthan

Check if value is in seq.

New in version 2.10.

Check if it’s possible to iterate over an object.

Same as a <= b.

Return true if the variable is lowercased.

Same as a < b.

< , lessthan

Return true if the object is a mapping (dict etc.).

New in version 2.6.

Same as a != b.

Return true if the variable is none.

Return true if the variable is a number.

Return true if the variable is odd.

Check if an object points to the same memory address than another object:

Return true if the variable is a sequence. Sequences are variables that are iterable.

Return true if the object is a string.

Like defined() but the other way round.

Return true if the variable is uppercased.

List of Global Functions ¶

The following functions are available in the global scope by default:

Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1] ; start (!) defaults to 0 . When step is given, it specifies the increment (or decrement). For example, range(4) and range(0, 4, 1) return [0, 1, 2, 3] . The end point is omitted! These are exactly the valid indices for a list of 4 elements.

This is useful to repeat a template block multiple times, e.g. to fill a list. Imagine you have 7 users in the list but you want to render three empty items to enforce a height with CSS:

Generates some lorem ipsum for the template. By default, five paragraphs of HTML are generated with each paragraph between 20 and 100 words. If html is False, regular text is returned. This is useful to generate simple contents for layout testing.

A convenient alternative to dict literals. {'foo': 'bar'} is the same as dict(foo='bar') .

The cycler allows you to cycle among values similar to how loop.cycle works. Unlike loop.cycle , you can use this cycler outside of loops or over multiple loops.

This can be very useful if you want to show a list of folders and files with the folders on top but both in the same list with alternating row colors.

The following example shows how cycler can be used:

A cycler has the following attributes and methods:

Resets the cycle to the first item.

Goes one item ahead and returns the then-current item.

Returns the current item.

New in version 2.1.

A tiny helper that can be used to “join” multiple sections. A joiner is passed a string and will return that string every time it’s called, except the first time (in which case it returns an empty string). You can use this to join things:

Creates a new container that allows attribute assignment using the {% set %} tag:

The main purpose of this is to allow carrying a value from within a loop body to an outer scope. Initial values can be provided as a dict, as keyword arguments, or both (same behavior as Python’s dict constructor):

Extensions ¶

The following sections cover the built-in Jinja2 extensions that may be enabled by an application. An application could also provide further extensions not covered by this documentation; in which case there should be a separate document explaining said extensions .

If the i18n extension is enabled, it’s possible to mark parts in the template as translatable. To mark a section as translatable, you can use trans :

To translate a template expression — say, using template filters, or by just accessing an attribute of an object — you need to bind the expression to a name for use within the translation block:

If you need to bind more than one expression inside a trans tag, separate the pieces with a comma ( , ):

Inside trans tags no statements are allowed, only variable tags are.

To pluralize, specify both the singular and plural forms with the pluralize tag, which appears between trans and endtrans :

By default, the first variable in a block is used to determine the correct singular or plural form. If that doesn’t work out, you can specify the name which should be used for pluralizing by adding it as parameter to pluralize :

When translating longer blocks of text, whitespace and linebreaks result in rather ugly and error-prone translation strings. To avoid this, a trans block can be marked as trimmed which will replace all linebreaks and the whitespace surrounding them with a single space and remove leading/trailing whitespace:

If trimming is enabled globally, the notrimmed modifier can be used to disable it for a trans block.

New in version 2.10: The trimmed and notrimmed modifiers have been added.

It’s also possible to translate strings in expressions. For that purpose, three functions exist:

gettext : translate a single string

ngettext : translate a pluralizable string

_ : alias for gettext

For example, you can easily print a translated string like this:

To use placeholders, use the format filter:

For multiple placeholders, always use keyword arguments to format , as other languages may not use the words in the same order.

Changed in version 2.5.

If newstyle gettext calls are activated ( Whitespace Trimming ), using placeholders is a lot easier:

Note that the ngettext function’s format string automatically receives the count as a num parameter in addition to the regular parameters.

Expression Statement ¶

If the expression-statement extension is loaded, a tag called do is available that works exactly like the regular variable expression ( {{ ... }} ); except it doesn’t print anything. This can be used to modify lists:

Loop Controls ¶

If the application enables the Loop Controls , it’s possible to use break and continue in loops. When break is reached, the loop is terminated; if continue is reached, the processing is stopped and continues with the next iteration.

Here’s a loop that skips every second item:

Likewise, a loop that stops processing after the 10th iteration:

Note that loop.index starts with 1, and loop.index0 starts with 0 (See: For ).

With Statement ¶

New in version 2.3.

The with statement makes it possible to create a new inner scope. Variables set within this scope are not visible outside of the scope.

With in a nutshell:

Because it is common to set variables at the beginning of the scope, you can do that within the with statement. The following two examples are equivalent:

An important note on scoping here. In Jinja versions before 2.9 the behavior of referencing one variable to another had some unintended consequences. In particular one variable could refer to another defined in the same with block’s opening statement. This caused issues with the cleaned up scoping behavior and has since been improved. In particular in newer Jinja2 versions the following code always refers to the variable a from outside the with block:

In earlier Jinja versions the b attribute would refer to the results of the first attribute. If you depend on this behavior you can rewrite it to use the set tag:

In older versions of Jinja (before 2.9) it was required to enable this feature with an extension. It’s now enabled by default.

Autoescape Overrides ¶

New in version 2.4.

If you want you can activate and deactivate Autoescaping from within a template.

After an endautoescape the behavior is reverted to what it was before.

Logo

  • Whitespace Control
  • Line Statements
  • Base Template
  • Child Template
  • Super Blocks
  • Named Block End-Tags
  • Block Nesting and Scope
  • Template Objects
  • Working with Manual Escaping
  • Working with Automatic Escaping
  • Assignments
  • Block Assignments
  • Import Context Behavior
  • Comparisons
  • Other Operators
  • If Expression
  • Python Methods
  • List of Builtin Filters
  • List of Builtin Tests
  • List of Global Functions
  • Expression Statement
  • Loop Controls
  • With Statement
  • Autoescape Overrides
  • Next: Extensions

Quick search

  • What is SQL
  • SQL in PushMetrics
  • Basic query syntax
  • Basic query syntax, part 2
  • Grouping data
  • Joining data
  • Subqueries & CTEs
  • Window functions

Learn Jinja

  • What is Jinja?
  • Conditionals
  • Template inheritance
  • Real World examples
  • Why Jinja and SQL?
  • Jinja & SQL Quiz

Data Terminology

  • What is a DAG?
  • What is ETL ?
  • What is the Modern Data Stack?
  • What is Reverse ETL?
  • What is Operational Analytics?
  • What is KPI reporting?
  • What is idempotency?
  • What does 'data grain' mean?

Variables let you inject data in your template. In PushMetrics, they're called parameters .

Jinja variables in Python

Working in Python, the simplest way to set variables is as a Dictionary . You can then use your dictionary as an argument for the .render() method of the Jinja Template.

Jinja variables in SQL

You can set variables in your SQL template just like you would do for any other Jinja template. The following code would result in the same query as the code in the example above:

Why would you use Jinja variables in SQL?

To reduce (or avoid altogether) repetition. Consider the follow CTE query:

Using day_param you can reuse the same query with different values.

Variables in PushMetrics

There are two ways in PushMetrics to set variables that are then available in throughout your notebook, including all SQL, API, Email, or Slack blocks.

1. Parameter Blocks

Create a _parameter block_ and reference its name in SQL

2. Jinja in text blocks

In PushMetrics you can write Jinja anywhere. To create a variable you can use the following Syntax:

The value of parameter will then be available to all following blocks defined in the notebook.

  • --> New & extended components --> The Editor --> 1.2 - Adding a cover image --> File structure --> Gulp file includes --> Customizing SCSS -->