Skip to content

Commit

Permalink
Docs for jinja2_environment_from_request hook, refs #2225
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jan 5, 2024
1 parent b43d5c3 commit 8beff57
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions docs/plugin_hooks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1136,13 +1136,36 @@ jinja2_environment_from_request(datasette, request, env)
``datasette`` - :ref:`internals_datasette`
A Datasette instance.

``request`` - :ref:`internals_request`
The current HTTP request.
``request`` - :ref:`internals_request` or ``None``
The current HTTP request, if one is available.

``env`` - `Environment`
``env`` - ``Environment``
The Jinja2 environment that will be used to render the current page.

... use overlays here
This hook can be used to return a customized `Jinja environment <https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment>`__ based on the incoming request.

If you want to run a single Datasette instance that serves different content for different domains, you can do so like this:

.. code-block:: python
from datasette import hookimpl
from jinja2 import ChoiceLoader, FileSystemLoader
@hookimpl
def jinja2_environment_from_request(request, env):
if request and request.host == "www.niche-museums.com":
return env.overlay(
loader=ChoiceLoader(
[
FileSystemLoader("/mnt/niche-museums/templates"),
env.loader,
]
),
enable_async=True,
)
return env
This uses the Jinja `overlay() method <https://jinja.palletsprojects.com/en/3.0.x/api/#jinja2.Environment.overlay>`__ to create a new environment identical to the default environment except for having a different template loader, which first looks in the ``/mnt/niche-museums/templates`` directory before falling back on the default loader.

.. _plugin_hook_filters_from_request:

Expand Down

0 comments on commit 8beff57

Please sign in to comment.