Template Rendering in Flask is a feature that allows you to serve dynamic HTML pages by rendering templates with data provided by your Flask application. The default templating engine for Flask is Jinja2, which is installed automatically when you install Flask.
Here are the possible options for template rendering in Flask:
- Basic Template Rendering:
To render a template, you can use the render_template
function provided by Flask. This function takes the name of the template file (relative to the templates
folder) as its first argument and a dictionary of variables as its second argument.
Example:
In app.py
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', name='World')
In templates/index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Hello, {{ name }}!</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
- Template Inheritance:
Jinja2 supports template inheritance, which allows you to define a base template that contains the common elements of your HTML pages, and then extend that base template in other templates.
Example:
In templates/base.html
:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<div id="header">
<h1>My Website</h1>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
In templates/index.html
:
{% extends 'base.html' %}
{% block title %}Index Page{% endblock %}
{% block content %}
<h2>Welcome to the Index Page!</h2>
{% endblock %}
- Filters:
Jinja2 provides a variety of filters that you can use to format the data in your templates. For example, you can use the safe
filter to mark a string as safe for HTML output, or the upper
filter to convert a string to uppercase.
Example:
In templates/index.html
:
<p>{{ name | upper }}</p>
<p>{% if name %}{{ name | safe }}{% else %}No name provided{% endif %}</p>
Sources:
- https://developers.redhat.com/articles/2023/09/05/beginners-guide-python-containers
- https://sweetcode.io/automate-whatsapp-messages-using-twilio-and-flask
- https://code.visualstudio.com/docs/python/tutorial-flask
- https://devoops.blog/kubernetes-pods-extractor
- https://sweetcode.io/how-to-take-zoom-attendance-with-python
- https://www.educative.io/blog/python-flask-tutorial