Welcome to our comprehensive guide on Jinja2 Template Reference, a powerful tool used in Flask for rendering HTML templates dynamically. Let's dive in!
Jinja2 is a powerful templating engine that Flask, a popular Python web framework, uses to separate the application logic from the presentation layer. In simple terms, it helps you create dynamic web pages.
Jinja2 is a simple, yet powerful, template engine for Python. It allows you to create dynamic web pages by using placeholders for variables, control structures, and even small programs.
To use Jinja2 in your Flask application, you first need to install it using pip install Jinja2. Once installed, Flask automatically includes it in your application.
Let's create a simple HTML page using Jinja2.
<!DOCTYPE html>
<html>
<head>
<title>My First Jinja2 Template</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>In the above example, {{ name }} is a placeholder for a variable that will be passed to the template.
To pass variables to your template, you can use the render_template function in your Flask app.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
name = 'John Doe'
return render_template('home.html', name=name)
if __name__ == '__main__':
app.run(debug=True)In the above code, we define a route that returns the home.html template with the name variable set to 'John Doe'.
You can use the if statement to conditionally render parts of your template.
{% if condition %}
<!-- content to render if condition is true -->
{% endif %}You can use the for loop to iterate over a list or other iterable.
{% for item in sequence %}
<!-- content to render for each item -->
{% endfor %}Which function in Flask is used to render templates with variables?
You can create a base template that other templates can inherit from. This helps to reduce repetition and maintain consistency across your templates.
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<!-- other common elements -->
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<!-- other common elements -->
</body>
</html>In the above example, the title and content sections are blocks that can be overridden in child templates.
Filters are used to transform the output of variables. For example, you can use the upper filter to convert text to uppercase.
{{ name|upper }}In the above example, |upper applies the upper filter to the name variable.
You've now learned the basics of Jinja2, a powerful templating engine used in Flask. You've seen how to pass variables, use control structures, extend templates, and apply filters. Happy coding! 🚀
Stay tuned for more advanced Jinja2 concepts in our future tutorials. 💡