Using variables in templates
Flask is a popular web framework for Python and it uses the Jinja2 template engine to generate dynamic web pages. One of the most powerful features of Jinja2 is its ability to use variables in templates. In this tutorial, we will explore how to use variables in Flask templates, an essential skill for any Flask developer.
What is a Variable in Flask Templates?
A variable in Flask templates is a placeholder for a value that can change. It is usually data that you want to display in your HTML templates. Variables in Flask templates are defined in your Python script and then passed to the template to be rendered.
How to Define Variables in Flask
Before we can use a variable in a template, we need to define it in our Flask application. Let's say we have a Flask route that looks like this:
@app.route('/')
def home():
return render_template('home.html')
We can define a variable in the home()
function and pass it to our home.html
template using the render_template
function. Here's how to do it:
@app.route('/')
def home():
greeting = "Hello, Flask learners!"
return render_template('home.html', greeting=greeting)
In this code, we're defining a variable greeting
and assigning it the value "Hello, Flask learners!". We then pass this variable to our home.html
template.
How to Use Variables in Templates
Now that we have passed our greeting
variable to our home.html
template, we can use it in the template. Here's how to do it:
<!DOCTYPE html>
<html>
<body>
<h1>{{ greeting }}</h1>
</body>
</html>
In this code, {{ greeting }}
is a placeholder for our greeting
variable. When Flask renders this template, it will replace {{ greeting }}
with the value of the greeting
variable, which is "Hello, Flask learners!".
Using Variables in Loops and Conditionals
You can also use variables in loops and conditionals in your Flask templates. Here's an example of using a variable in a loop:
@app.route('/')
def home():
items = ['Flask', 'Jinja2', 'Python']
return render_template('home.html', items=items)
And in the home.html
template:
<!DOCTYPE html>
<html>
<body>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
In this code, we're defining a variable items
and assigning it a list of strings. We then pass this variable to our home.html
template. In the template, we use a for loop to iterate over each item in the items
list and print it.
That's it! You now know how to use variables in Flask templates. Practice using variables, loops, and conditionals in your own Flask applications to become more proficient. Happy coding!