Displaying Dynamic Content with Jinja2 Templates
Displaying Dynamic Content with Jinja2 Templates
Welcome back! Previously, you learned how to render a simple HTML template using Flask. In this lesson, we’ll go a step further and explore how to render templates with dynamic content. This will enable us to create more personalized and interactive web pages.
Dynamic content is key because it lets us tailor the user experience based on various inputs, such as user data or database queries. By the end of this lesson, you'll learn how to pass data from your Flask application to your HTML templates using Jinja2, allowing for personalized user experiences.
Understanding Static vs. Dynamic Content
Static content remains unchanged regardless of user interaction. For example, the HTML code you wrote in the welcome.html file provided a static welcome message. While useful, static content doesn't adapt based on user input or data, which can limit its effectiveness.
Dynamic content, however, changes based on factors like user interactions, database entries, or even random events. This type of content is essential for creating personalized and engaging user experiences. In this lesson, we'll learn how to pass variables from our Flask app to our HTML templates, enabling us to render dynamic content.
Jinja2 Templating Engine
Flask uses the Jinja2 templating engine to achieve this. A templating engine is a tool that combines templates with data to generate dynamic HTML. Jinja2 allows us to embed Python-like expressions directly within our HTML files. These expressions are evaluated and replaced with actual data at the time of rendering. For example, you can use Jinja2 to insert variables, apply logic, and loop through data structures within your HTML. This makes it easy to create HTML that can dynamically change based on the variables passed from your Flask applications.
Passing Variables to Templates
In Flask, you can pass variables from your Python code to your HTML templates using the render_template function. For instance, let’s say we want to pass a variable called name to our template to personalize our welcome message.
Here's how we can update our app.py to achieve this:
In the welcome function, we assign the value "User" to the variable name and pass it to welcome.html using render_template.
