You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
49 Min
59 Seg
Curso de Flask

Curso de Flask

Luis Mart铆nez

Luis Mart铆nez

Plantillas con Jinja en Flask

4/18
Resources

The integration of Jinja into Flask revolutionizes the way we create dynamic web applications by allowing us to embed programming logic directly into our HTML files. This powerful combination gives us the flexibility to develop custom, interactive user interfaces without sacrificing HTML structure and semantics. Let's discover how Jinja transforms web development with Flask and how we can leverage its capabilities to create more robust and dynamic applications.

What is Jinja and why is it important in Flask?

Jinja is a Python templating engine that allows you to embed variables, conditionals, loops and other programming structures directly into HTML files. Unlike static HTML, Jinja allows us to create dynamic content that is generated at runtime.

Main features of Jinja:

  • Use of variables within HTML.
  • Conditional structures (if-else)
  • Loops (for)
  • Template inheritance
  • Filters to manipulate data

Flask integrates Jinja natively, which greatly facilitates the development of web applications with dynamic content. This integration is fundamental because it separates the business logic (Python) from the presentation (HTML), maintaining a cleaner and more maintainable code.

How to implement Jinja templates in Flask?

To start using Jinja in our Flask application, we need to follow some basic steps:

Creating the folder structure.

The first step is to create a folder called templates in the root of our project. Flask will automatically look for HTML files in this folder when we use the render_template function.

# Basic structure of the project/project /templates home.html app.py

Rendering basic templates

To render a template, we use the render_template function that we must import from Flask:

from flask import Flask, render_template
app = Flask(__name__)
 @app.route('/')def home(): return render_template('home.html')

This code simply renders the HTML file without any dynamic variable. To verify that it works correctly, we can access the main route of our application and view the source code, which should show exactly the content of our HTML file.

Passing variables to templates

One of Jinja's most powerful features is the ability to pass variables from Python to our HTML templates:

@app.route('/')def home(): rol = "admin" return render_template('home.html',  rol=rol).

In the HTML file, we can access this variable using double braces syntax:

<p>You are{{ role }}</p>

When Flask renders this template, it will replace {{ role }} with the value of the variable, in this case "admin".

How to use control structures in Jinja?

Jinja allows us to use control structures such as conditionals and loops directly in our HTML, which makes our templates much more dynamic.

Conditionals (if-else)

Conditionals allow us to show or hide HTML elements according to certain conditions:

{% if role == "admin" %} <button>Delete</button>{% else %} <button>RequestDelete</button>{% endif %}

In this example, if the user has the administrator role, you will see a "Delete" button. Otherwise, he will see a "Request Delete" button. This functionality is especially useful for controlling access to certain features based on the user's role.

Loops (for)

Loops allow us to iterate over collections of data and generate HTML dynamically:

@app.route('/')def home(): rol = "normal" notes = ["Note one", "Note two", "Note three"] return render_template('home.html',  rol=rol,  notes=notes).

In the HTML, we can iterate over this list:

<ul> {% for note in notes %} <li>{{ note }}</li> {% endfor %}</ul>

This code will generate an HTML list with a <li> element for each note in our list. In real applications, these notes could come from a database, which makes this functionality extremely useful.

Improving the development experience with Jinja

To make it easier to work with Jinja, it is advisable to install extensions in our code editor. For example, in Visual Studio Code, there is an extension called "Jinja" that provides syntax highlighting and auto-completion for Jinja code.

Benefits of using extensions for Jinja:

  • Syntax highlighting to easily distinguish Jinja code from HTML.
  • Auto-completion of structures such as {% if %}, {% for %}, etc.
  • Improved code readability
  • Syntax error detection

These tools significantly improve productivity when working with Jinja templates, especially in large projects with multiple HTML files.

Working with objects and dictionaries

Instead of passing simple strings to our templates, we can pass more complex data structures such as dictionaries or objects:

@app.route('/')def home(): notes = [ {"title": "Note one", "description": "Description of note one", "created_at": "2023-01-01"}, {"title": "Note two", "description": "Description of note two", "created_at": "2023-01-02"}, {"title": "Note three", "description": "Description of note three", "created_at": "2023-01-03"} ] return render_template('home.html',  notes=notes)

In the template, we can access the properties of each object:

<ul> {% for note in notes %} <li> <h3>{{ note.title }}</h3> <p>{{ note.description }}</p> <small>Createdon: {{ note.created_at }}</small> </li> {% endfor %}</ul>.

This capability allows us to create much richer and more detailed interfaces, showing multiple aspects of our data.

Jinja is a powerful tool that transforms the way we develop web applications with Flask. By mastering its basic functionalities, we can create dynamic and custom interfaces that significantly improve the user experience. I encourage you to explore more Jinja features in the official documentation and experiment with more complex data structures in your projects. What other Jinja features would you like to implement in your Flask applications? Share your ideas and experiences in the comments.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Esta bueno Jinja, no sabia que viene integrado en Flask