Basics

Jinja Syntax

Jinja Syntax Basics

Jinja syntax uses {{ }} for variables and {% %} for logic.

Introduction to Jinja Syntax

Jinja is a popular templating engine for Python, used to generate dynamic HTML content. It allows you to embed Python-like expressions and statements into your HTML files. The basic syntax revolves around two types of delimiters: {{ ... }} for expressions and variables, and {% ... %} for logic such as loops and conditionals.

Using Variables in Jinja

To display a variable in a Jinja template, you use the {{ ... }} syntax. This will output the value of the variable within your HTML.

Control Structures in Jinja

Jinja uses {% ... %} delimiters for control structures such as loops and conditionals. These allow you to control the flow of the template rendering.

If Statements

The if statement evaluates a condition and renders content based on whether the condition is true or false.

For Loops

The for loop iterates over a sequence, such as a list or a dictionary. This is useful for displaying lists of items dynamically.

Commenting in Jinja

To add comments in Jinja that won't be rendered in the final output, use the {# ... #} syntax. This is helpful for leaving notes or explanations within your templates.

Conclusion

Jinja syntax is a powerful tool for creating dynamic web pages with Python. Understanding how to use variables, control structures, and comments allows you to build more flexible and interactive templates. In the next post, we will delve deeper into handling variables within Jinja templates.

Previous
Setup