Jinja 2
Introduction
Jinja2 is a powerful templating engine for Python, widely used for rendering dynamic HTML content. Nexios, as a Python framework, allows seamless integration with Jinja2 for building robust web applications with templating support.
Installation
To integrate Jinja2 with Nexios, first ensure Jinja2 is installed in your environment:
Configuring Jinja2 in Nexios
Nexios supports Jinja2 out-of-the-box, but you need to configure the template directory and environment settings. Here’s how you can set it up:
Explanation of Configuration
FileSystemLoader(template_dir)
: Loads templates from the specified directory.autoescape=True
: Ensures safe HTML rendering to prevent XSS attacks.trim_blocks=True
andlstrip_blocks=True
: Improve readability by removing excess whitespace.
Rendering Templates in Nexios
Once Jinja2 is set up, you can render templates dynamically within Nexios views.
Example: Rendering a Simple Template
Assume you have a index.html
file inside the templates/
folder:
Now, render it inside a Nexios route:
Using Jinja2 Features
Jinja2 provides various features such as:
Variables:
{{ variable }}
Filters:
{{ name|upper }}
(Converts text to uppercase)Loops:
<div data-gb-custom-block data-tag="for"> {{ user }} </div>
(Iterates over lists)Conditionals:
<div data-gb-custom-block data-tag="if"> Welcome Admin </div>
(Handles logic)Macros:
<div data-gb-custom-block data-tag="macro"> Hello, {{ name }}! </div>
(Reusable components)
Example: Using Loops and Conditionals
Example: Using Macros
Macros allow you to create reusable snippets of code.
Template Inheritance
Jinja2 supports template inheritance to maintain a consistent layout across pages.
Example: Base Template (base.html
)
base.html
)Extending the Base Template (home.html
)
home.html
)