Variables

Jinja Template Variables

Working with Template Variables

Jinja template variables render Python data with {{ }}.

Introduction to Jinja Template Variables

Jinja is a popular templating engine for Python, allowing developers to create dynamic web applications by embedding Python expressions within HTML. Jinja template variables are enclosed in {{ ... }} and are used to render Python data directly into templates.

Basic Usage of Template Variables

Template variables can be used to display dynamic data in your templates. To use template variables, you first need to pass data from your Python code to the template. This is typically done by rendering a template with a context dictionary that contains key-value pairs, where the key is the variable name, and the value is the data you want to render.

In the example above, the data dictionary contains two keys: name and age. When you render the hello.html template, these variables become available for use within the template.

When the template is rendered, the placeholders {{ name }} and {{ age }} are replaced with 'John' and '30', respectively, resulting in the output:

Using Variables in Conditional Statements

Jinja allows you to use variables within conditional statements to control the flow of your template rendering. This enables you to dynamically alter the displayed content based on variable values.

In this example, if the variable age is 18 or older, the template will display "You are an adult." Otherwise, it will display "You are a minor."

Looping Through Variables

Jinja also supports looping through variables, making it easy to display lists or arrays of data within your templates. You can use the {% for %} statement to iterate over a sequence.

The example above will loop through each user in the users list, generating a list item for each user's name. The resulting HTML will look like this:

Escaping Variables

By default, Jinja escapes variables for safe HTML output, preventing XSS attacks. If you need to render raw HTML, use the |safe filter, but use it cautiously.

When using the |safe filter, ensure that the data is thoroughly sanitized to avoid security vulnerabilities.