Enhance templating documentation with examples
Updated the templating documentation to clarify Jinja's setup and usage, including examples for using `url_for` and streaming templates.
This commit is contained in:
parent
2579ce9f18
commit
cce7db83a0
1 changed files with 95 additions and 31 deletions
|
|
@ -1,11 +1,13 @@
|
||||||
Templates
|
Templates
|
||||||
=========
|
=========
|
||||||
|
|
||||||
Flask leverages Jinja as its template engine. You are obviously free to use
|
Flask leverages Jinja as its template engine. You are free to use
|
||||||
a different template engine, but you still have to install Jinja to run
|
a different template engine, but you still have to install Jinja to run
|
||||||
Flask itself. This requirement is necessary to enable rich extensions.
|
Flask itself. This requirement is necessary to enable rich extensions.
|
||||||
An extension can depend on Jinja being present.
|
An extension can depend on Jinja being present.
|
||||||
|
|
||||||
|
Note: Flask's template rendering behavior is explained in more detail in the official Jinja documentation linked below.
|
||||||
|
|
||||||
This section only gives a very quick introduction into how Jinja
|
This section only gives a very quick introduction into how Jinja
|
||||||
is integrated into Flask. If you want information on the template
|
is integrated into Flask. If you want information on the template
|
||||||
engine's syntax itself, head over to the official `Jinja Template
|
engine's syntax itself, head over to the official `Jinja Template
|
||||||
|
|
@ -15,18 +17,20 @@ more information.
|
||||||
Jinja Setup
|
Jinja Setup
|
||||||
-----------
|
-----------
|
||||||
|
|
||||||
Unless customized, Jinja is configured by Flask as follows:
|
Flask sets up Jinja with some default behavior to keep templates safe and easy to work with:
|
||||||
|
|
||||||
- autoescaping is enabled for all templates ending in ``.html``,
|
- When rendering templates with :func:`~flask.templating.render_template`, autoescaping
|
||||||
``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using
|
is turned on for files ending in ``.html``, ``.htm``, ``.xml``, ``.xhtml`` and ``.svg``.
|
||||||
:func:`~flask.templating.render_template`.
|
This avoids accidental HTML or XML injection.
|
||||||
- autoescaping is enabled for all strings when using
|
|
||||||
:func:`~flask.templating.render_template_string`.
|
- With :func:`~flask.templating.render_template_string`, all output is autoescaped
|
||||||
- a template has the ability to opt in/out autoescaping with the
|
since there is no file extension to determine behavior.
|
||||||
``{% autoescape %}`` tag.
|
|
||||||
- Flask inserts a couple of global functions and helpers into the
|
- Templates can turn autoescaping on or off using the ``{% autoescape %}`` block when
|
||||||
Jinja context, additionally to the values that are present by
|
more control is needed.
|
||||||
default.
|
|
||||||
|
- Flask also adds a few helpful global utilities to the Jinja context so they can be
|
||||||
|
used directly in templates without extra setup.
|
||||||
|
|
||||||
Standard Context
|
Standard Context
|
||||||
----------------
|
----------------
|
||||||
|
|
@ -65,15 +69,57 @@ by default:
|
||||||
variable is unavailable if the template was rendered without an active
|
variable is unavailable if the template was rendered without an active
|
||||||
request context.
|
request context.
|
||||||
|
|
||||||
.. function:: url_for
|
Using `url_for` in Templates
|
||||||
|
----------------------------
|
||||||
|
|
||||||
|
Flask provides the `url_for` function to dynamically build URLs based on the names of view functions instead of hard-coding paths directly in templates. This allows your application to remain maintainable and flexible as route definitions evolve. When route paths are modified or moved, templates using `url_for` will continue to work without requiring any changes.
|
||||||
|
|
||||||
|
Consider the following view function:
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
|
@app.route('/user/<username>')
|
||||||
|
def profile(username):
|
||||||
|
return f"Profile: {username}"
|
||||||
|
|
||||||
|
Inside a Jinja template, the corresponding link can be generated with:
|
||||||
|
|
||||||
|
.. code-block:: html
|
||||||
|
|
||||||
|
<a href="{{ url_for('profile', username='alice') }}">View Profile</a>
|
||||||
|
|
||||||
|
This will render to:
|
||||||
|
|
||||||
|
.. code-block:: text
|
||||||
|
|
||||||
|
/user/alice
|
||||||
|
|
||||||
|
Using `url_for` is recommended over hard-coded links such as `/user/alice`, because it keeps the routing logic and template usage consistent and reduces the potential for broken links within the application.
|
||||||
|
|
||||||
|
Using `url_for` for Static Files
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
In addition to generating links for dynamic routes, `url_for` can also be used to reference static assets such as images, stylesheets, or JavaScript files. Flask makes files located inside the ``static`` directory available under the ``static`` endpoint.
|
||||||
|
|
||||||
|
Example usage in a template:
|
||||||
|
|
||||||
|
.. code-block:: html
|
||||||
|
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
|
|
||||||
|
This ensures that static file references remain valid even when configured to serve from a different location, a CDN, or when additional cache-busting strategies are applied.
|
||||||
|
|
||||||
|
.. function:: url_for(endpoint, **values)
|
||||||
:noindex:
|
:noindex:
|
||||||
|
|
||||||
The :func:`flask.url_for` function.
|
Builds a URL to a given endpoint. Commonly used to link to routes or static files
|
||||||
|
directly from templates.
|
||||||
|
|
||||||
.. function:: get_flashed_messages
|
.. function:: get_flashed_messages(with_categories=False, category_filter=())
|
||||||
:noindex:
|
:noindex:
|
||||||
|
|
||||||
The :func:`flask.get_flashed_messages` function.
|
Retrieves flash messages that were stored during the request cycle for display
|
||||||
|
in templates.
|
||||||
|
|
||||||
.. admonition:: The Jinja Context Behavior
|
.. admonition:: The Jinja Context Behavior
|
||||||
|
|
||||||
|
|
@ -95,7 +141,6 @@ by default:
|
||||||
|
|
||||||
{% from '_helpers.html' import my_macro with context %}
|
{% from '_helpers.html' import my_macro with context %}
|
||||||
|
|
||||||
|
|
||||||
Controlling Autoescaping
|
Controlling Autoescaping
|
||||||
------------------------
|
------------------------
|
||||||
|
|
||||||
|
|
@ -183,13 +228,12 @@ For template tests, use the :meth:`~.Flask.template_test` decorator or
|
||||||
method.
|
method.
|
||||||
|
|
||||||
The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to
|
The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to
|
||||||
indicate that the registered functions will be avaialble to all templates, not
|
indicate that the registered functions will be available to all templates, not
|
||||||
only when rendering from within the blueprint.
|
only when rendering from within the blueprint.
|
||||||
|
|
||||||
The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be
|
The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be
|
||||||
modified directly, as you would when using Jinja outside Flask.
|
modified directly, as you would when using Jinja outside Flask.
|
||||||
|
|
||||||
|
|
||||||
Context Processors
|
Context Processors
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
|
|
@ -200,6 +244,11 @@ template context. A context processor is a function that returns a
|
||||||
dictionary. The keys and values of this dictionary are then merged with
|
dictionary. The keys and values of this dictionary are then merged with
|
||||||
the template context, for all templates in the app::
|
the template context, for all templates in the app::
|
||||||
|
|
||||||
|
Example: Injecting a User Object
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def inject_user():
|
def inject_user():
|
||||||
return dict(user=g.user)
|
return dict(user=g.user)
|
||||||
|
|
@ -213,6 +262,11 @@ Variables are not limited to values; a context processor can also make
|
||||||
functions available to templates (since Python allows passing around
|
functions available to templates (since Python allows passing around
|
||||||
functions)::
|
functions)::
|
||||||
|
|
||||||
|
Example: Registering a Utility Function
|
||||||
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
.. code-block:: python
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def utility_processor():
|
def utility_processor():
|
||||||
def format_price(amount, currency="€"):
|
def format_price(amount, currency="€"):
|
||||||
|
|
@ -231,16 +285,26 @@ context processor.
|
||||||
Streaming
|
Streaming
|
||||||
---------
|
---------
|
||||||
|
|
||||||
It can be useful to not render the whole template as one complete
|
Rather than rendering the entire template into a single large string, it can be
|
||||||
string, instead render it as a stream, yielding smaller incremental
|
rendered in smaller pieces and returned as a stream. This allows the application
|
||||||
strings. This can be used for streaming HTML in chunks to speed up
|
to send partial output to the client sooner.
|
||||||
initial page load, or to save memory when rendering a very large
|
|
||||||
template.
|
|
||||||
|
|
||||||
The Jinja template engine supports rendering a template piece
|
Streaming can be helpful in scenarios such as:
|
||||||
by piece, returning an iterator of strings. Flask provides the
|
|
||||||
:func:`~flask.stream_template` and :func:`~flask.stream_template_string`
|
- improving initial page load times by sending HTML chunks as they are ready
|
||||||
functions to make this easier to use.
|
- reducing memory usage when working with very large templates
|
||||||
|
|
||||||
|
Streaming Templates
|
||||||
|
^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
Jinja allows templates to be rendered incrementally, producing a stream of
|
||||||
|
string fragments instead of a single consolidated output. This enables
|
||||||
|
applications to send partial responses as they become available.
|
||||||
|
|
||||||
|
Flask exposes helpers to simplify streamed rendering:
|
||||||
|
|
||||||
|
- :func:`~flask.stream_template` — streams a template file.
|
||||||
|
- :func:`~flask.stream_template_string` — streams a template given as a string.
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
|
|
@ -250,6 +314,6 @@ functions to make this easier to use.
|
||||||
def timeline():
|
def timeline():
|
||||||
return stream_template("timeline.html")
|
return stream_template("timeline.html")
|
||||||
|
|
||||||
These functions automatically apply the
|
Function Behavior
|
||||||
:func:`~flask.stream_with_context` wrapper if a request is active, so
|
^^^^^^^^^^^^^^^^^
|
||||||
that it remains available in the template.
|
When a request is active, these functions automatically apply the :func:`~flask.stream_with_context` wrapper, ensuring the request context remains available in the template.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue