Flask Jinja2
What is Jinja2?
Jinja2 is a powerful templating engine for Python, used by Flask to generate dynamic HTML pages. It allows developers to embed Python-like expressions and control structures within HTML templates, enabling features like variable substitution, loops, conditionals, and template inheritance. Jinja2 provides a clean way to separate the presentation layer (HTML) from the logic (Python) in web applications.
What are Jinja2 template delimiters?
Jinja2 uses specific delimiters to distinguish between template expressions and standard HTML. The main delimiters are:
{{ ... }}: Used for variable substitution, where the expression inside is evaluated and rendered.{% ... %}: Used for control structures like loops and conditionals.{# ... #}: Used for comments that won't be rendered in the output HTML.{% extends %}and{% block %}: Used for template inheritance and defining blocks.
Example:
<p>Hello, {{ username }}!</p>
{% if is_admin %}
<p>You have admin privileges.</p>
{% else %}
<p>Welcome, user.</p>
{% endif %}
In this example, {{ username }} renders the value of the username variable, and the {% if %} control structure displays different content based on whether the user is an admin.
How do you use variables in Jinja2 templates?
Variables in Jinja2 templates are used to insert dynamic content into HTML. They are enclosed in double curly braces {{ }}, and Flask passes these variables from view functions to the template using the render_template() function.
Example of passing variables to a Jinja2 template:
@app.route('/greet')
def greet():
return render_template('greet.html', name="Alice")
In the template:
<p>Hello, {{ name }}!</p>
In this example, the name variable is passed from the view function and rendered inside the template as "Hello, Alice!".
How do you use filters in Jinja2?
Filters in Jinja2 are used to modify the value of variables before they are rendered. Filters are applied using a pipe (|) symbol and can perform actions like formatting, modifying strings, or working with lists.
Example of using filters in Jinja2:
<p>{{ "hello world" | upper }}</p>
<p>{{ price | round(2) }}</p>
In this example, upper converts the string to uppercase, and round rounds the price variable to two decimal places.
What are some common Jinja2 filters?
Some commonly used Jinja2 filters include:
upper: Converts a string to uppercase.lower: Converts a string to lowercase.length: Returns the length of a string, list, or dictionary.default: Provides a default value if the variable is undefined.safe: Marks a string as safe for rendering without HTML escaping.date: Formats a date or time object.join: Joins a list of items into a string with a separator.
Example of using the length and default filters:
<p>The list has {{ items|length }} items.</p>
<p>{{ user|default("Guest") }}</p>
In this example, the length filter returns the number of items in the items list, and the default filter ensures that if user is not provided, "Guest" is displayed.
How do you use control structures like conditionals and loops in Jinja2?
Jinja2 provides control structures like conditionals and loops to dynamically control the content that is rendered. Conditionals allow you to display content based on specific conditions, while loops allow you to iterate over lists or dictionaries.
Example of a conditional:
{% if is_admin %}
<p>Welcome, Admin!</p>
{% else %}
<p>Welcome, User!</p>
{% endif %}
Example of a loop:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
In the conditional example, the message changes depending on whether is_admin is true. In the loop example, Jinja2 iterates over the items list and renders each item inside a <li> element.
What is template inheritance in Jinja2?
Template inheritance in Jinja2 allows you to create a base template with common elements (like headers and footers) and extend it in other templates. This reduces duplication and makes it easier to maintain consistent layouts across different pages.
Example of a base template (base.html):
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>Header content</header>
{% block content %}{% endblock %}
<footer>Footer content</footer>
</body>
</html>
Example of extending the base template:
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Welcome to the Home Page</h1>
{% endblock %}
In this example, the child template extends base.html and overrides the title and content blocks, inheriting the structure of the base template.
What is the include directive in Jinja2?
The include directive in Jinja2 allows you to include another template inside your current template. This is useful for reusing small components like navigation bars, headers, or footers across multiple pages.
Example of using the include directive:
<html>
<body>
{% include 'navbar.html' %}
<h1>Main Content</h1>
{% include 'footer.html' %}
</body>
</html>
In this example, the navbar.html and footer.html templates are included in the main template, ensuring consistency across the website.
How do you escape content in Jinja2?
By default, Jinja2 escapes HTML special characters to prevent cross-site scripting (XSS) attacks. If you want to render a string as raw HTML, you can use the |safe filter to disable escaping.
Example of escaping content:
<p>{{ "bold" }}</p> {# Escaped by default #}
<p>{{ "bold"|safe }}</p> {# Rendered as raw HTML #}
In this example, the first <p> tag escapes the HTML, while the second tag uses the |safe filter to render the <strong> tag as raw HTML.
How do you create reusable macros in Jinja2?
Macros in Jinja2 are reusable blocks of code that can be called like functions within your templates. Macros are useful for defining frequently used HTML snippets like form inputs or buttons.
Example of defining a macro:
{% macro input_field(name, placeholder) %}
<input type="text" name="{{ name }}" placeholder="{{ placeholder }}">
{% endmacro %}
Example of using the macro:
{{ input_field('username', 'Enter your username') }}
In this example, the input_field macro is defined to generate text input fields, and it is called with specific arguments to render an input element.
How do you comment code in Jinja2 templates?
You can comment code in Jinja2 templates using the {# ... #} syntax. These comments will not be rendered in the HTML output and are useful for adding explanations or notes within your template files.
Example of a comment in Jinja2:
{# This is a comment and won't appear in the rendered HTML #}
<p>This is visible content</p>
In this example, the comment is only visible in the template source code and won't appear in the final HTML output.