Basics

Jinja Variables

Using Jinja Variables

Jinja variables render dynamic data with {{ variable }} syntax.

Introduction to Jinja Variables

Jinja is a popular templating engine for Python, used to render dynamic data in web applications. Variables in Jinja are crucial for this task, allowing you to embed Python-like expressions in your templates. The syntax for using Jinja variables is simple: you enclose the variable name within double curly braces, like so: {{ variable }}.

Basic Usage of Jinja Variables

To use a Jinja variable, you first need to pass it to the template from your Python code. This is typically done through a dictionary. Here's a basic example demonstrating this process:

In this example, the Python script creates a simple Jinja template that includes a variable name. The template.render() method is called with a dictionary where name is assigned the value 'Alice'. Jinja replaces {{ name }} with 'Alice' in the output.

Using Expressions with Jinja Variables

Jinja variables can also be used in expressions, allowing you to perform operations directly within your templates. This can include mathematical operations, string manipulation, and more. Here is an example:

In this example, the Jinja template uses an expression {{ quantity * price }} to calculate the total. The variables quantity and price are passed to the template, and the result of their multiplication is rendered in the output.

Setting Default Values for Jinja Variables

In some cases, a variable might not be provided to the template. To handle such situations gracefully, Jinja allows you to set default values using the default filter. Here's how it works:

This template uses the default filter to provide a fallback value 'Guest' if the name variable is not supplied. This ensures that the template renders correctly even when some data is missing.

Escaping Jinja Variables

Sometimes, you might want to display the Jinja variable syntax itself as a literal string in your templates. To do this, you can use the raw block to escape the variable syntax:

By wrapping the Jinja syntax within {% raw %} and {% endraw %} tags, you can prevent Jinja from interpreting it, allowing you to display it as plain text in your output.

Previous
Syntax