Flask Templates
What are templates in Flask?
Templates in Flask are files that contain the HTML code for rendering web pages. Flask uses the Jinja2 templating engine to dynamically generate HTML pages by combining Python code with HTML. Templates allow you to separate the presentation layer (HTML) from the logic of your application (Python), making it easier to manage and maintain your code.
Where are Flask templates stored?
By default, Flask looks for templates in a directory named templates/ in the root of your application. You store your HTML files in this directory, and Flask renders them when requested.
Example folder structure:
myapp/
├── app.py
├── templates/
│ ├── home.html
│ └── about.html
In this structure, the home.html and about.html files are stored in the templates/ directory.
How do you render a template in Flask?
You render a template in Flask using the render_template() function. This function takes the name of the template file and any variables you want to pass to the template as arguments, then renders the HTML content dynamically.
Example of rendering a template:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
In this example, the render_template('home.html') function renders the home.html template when the root URL (/) is accessed.
How do you pass variables to a template in Flask?
You can pass variables to a template in Flask by including them as keyword arguments in the render_template() function. These variables are then accessible within the template using the Jinja2 syntax.
Example of passing variables to a template:
@app.route('/user/<username>')
def show_user(username):
return render_template('user.html', username=username)
In this example, the username variable is passed to the user.html template, where it can be used to personalize the content.
In the template (user.html):
<h1>Hello, {{ username }}!</h1>
The variable {{ username }} is replaced with the value passed from the view function.
What is Jinja2, and how does it work in Flask?
Jinja2 is a powerful templating engine used by Flask to render HTML dynamically. It allows you to embed Python-like expressions in your HTML templates, enabling features like variable substitution, loops, conditionals, and template inheritance. Jinja2 uses double curly braces {{ }} for variable substitution and curly braces with percentage signs {% %} for control structures.
Example of using Jinja2 in a Flask template:
<h1>Welcome, {{ username }}!</h1>
{% if is_admin %}
<p>You have admin privileges.</p>
{% else %}
<p>You are a regular user.</p>
{% endif %}
In this example, Jinja2 is used to display the username and conditionally show a message based on whether the user is an admin.
How do you use control structures like loops and conditionals in Flask templates?
In Flask templates, you can use Jinja2 control structures like loops and conditionals to dynamically generate HTML content. Loops allow you to iterate over lists or dictionaries, while conditionals let you render different content based on specific conditions.
Example of using a loop in a Flask template:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
In this example, the for loop iterates over the items list, generating a list item for each element.
Example of using a conditional in a Flask template:
{% if user %}
<p>Hello, {{ user }}!</p>
{% else %}
<p>Hello, Guest!</p>
{% endif %}
In this example, the template checks if a user variable is provided and displays a personalized greeting if it exists, or shows a generic message otherwise.
How do you use template inheritance in Flask?
Template inheritance in Flask allows you to define a base template with common layout elements (like headers and footers) and extend this base template in other templates. This helps you avoid duplicating code across multiple templates.
Example of a base template (base.html):
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>Welcome to My Website</header>
{% block content %}{% endblock %}
<footer>Footer Information</footer>
</body>
</html>
In this example, base.html defines a common structure for the page with blocks for title and content that can be overridden by child templates.
Example of extending the base template:
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Welcome to the Home Page!</h1>
<p>This is the main content of the home page.</p>
{% endblock %}
In this example, the child template extends base.html and overrides the title and content blocks.
How do you include templates in other templates in Flask?
In Flask, you can include one template inside another using the {% include %} directive. This is useful for including common components like navigation bars or footers across multiple pages.
Example of including a template:
<html>
<body>
{% include 'navbar.html' %}
<h1>Main Content</h1>
{% include 'footer.html' %}
</body>
</html>
In this example, the navbar.html and footer.html templates are included in the main template to display the navigation bar and footer, respectively.
How do you escape HTML in Flask templates?
Flask automatically escapes any special HTML characters in template variables to prevent cross-site scripting (XSS) attacks. However, if you need to output raw HTML, you can use the |safe filter to bypass automatic escaping.
Example of escaping HTML:
<p>{{ user_input }}</p> {# Escaped by default #}
<p>{{ user_input|safe }}</p> {# Rendered as raw HTML #}
In this example, the first {{ user_input }} is escaped, while the second {{ user_input|safe }} renders raw HTML.
How do you create reusable template macros in Flask?
In Flask, you can create reusable template macros to define frequently used code snippets like form inputs or buttons. Macros are defined using the {% macro %} directive and can be called like functions within templates.
Example of defining a macro:
{% macro input_field(name, placeholder) %}
<input type="text" name="{{ name }}" placeholder="{{ placeholder }}">
{% endmacro %}
Example of using the macro:
{{ input_field('username', 'Enter your username') }}
In this example, the input_field macro is defined to generate text input fields, and it is called with specific arguments to render an input element in the template.
How do you handle template errors in Flask?
Template errors in Flask occur when there are issues with the template syntax or variable references. Common errors include missing variables, syntax mistakes, or undefined functions. Flask automatically logs template errors, and in development mode, detailed error messages are displayed in the browser to help you debug the issue.
To prevent errors from undefined variables, you can use the Jinja2 default filter:
{{ user|default('Guest') }}
In this example, if the user variable is not defined, the string "Guest" is displayed instead.