prepare_jinja2_environment(datasette) argument, refs #1809

This commit is contained in:
Simon Willison 2022-09-14 14:31:54 -07:00
commit b40872f5e5
5 changed files with 14 additions and 7 deletions

View file

@ -345,7 +345,7 @@ class Datasette:
self.jinja_env.filters["escape_sqlite"] = escape_sqlite
self.jinja_env.filters["to_css_class"] = to_css_class
# pylint: disable=no-member
pm.hook.prepare_jinja2_environment(env=self.jinja_env)
pm.hook.prepare_jinja2_environment(env=self.jinja_env, datasette=self)
self._register_renderers()
self._permission_checks = collections.deque(maxlen=200)

View file

@ -26,7 +26,7 @@ def prepare_connection(conn, database, datasette):
@hookspec
def prepare_jinja2_environment(env):
def prepare_jinja2_environment(env, datasette):
"""Modify Jinja2 template environment e.g. register custom template tags"""

View file

@ -61,12 +61,15 @@ Examples: `datasette-jellyfish <https://datasette.io/plugins/datasette-jellyfish
.. _plugin_hook_prepare_jinja2_environment:
prepare_jinja2_environment(env)
-------------------------------
prepare_jinja2_environment(env, datasette)
------------------------------------------
``env`` - jinja2 Environment
The template environment that is being prepared
``datasette`` - :ref:`internals_datasette`
You can use this to access plugin configuration options via ``datasette.plugin_config(your_plugin_name)``
This hook is called with the Jinja2 environment that is used to evaluate
Datasette HTML templates. You can use it to do things like `register custom
template filters <http://jinja.pocoo.org/docs/2.10/api/#custom-filters>`_, for
@ -85,6 +88,8 @@ You can now use this filter in your custom templates like so::
Table name: {{ table|uppercase }}
Examples: `datasette-edit-templates <https://datasette.io/plugins/datasette-edit-templates>`_
.. _plugin_hook_extra_template_vars:
extra_template_vars(template, database, table, columns, view_name, request, datasette)

View file

@ -142,8 +142,9 @@ def extra_template_vars(
@hookimpl
def prepare_jinja2_environment(env):
def prepare_jinja2_environment(env, datasette):
env.filters["format_numeric"] = lambda s: f"{float(s):,.0f}"
env.filters["to_hello"] = lambda s: datasette._HELLO
@hookimpl

View file

@ -545,11 +545,12 @@ def test_hook_register_output_renderer_can_render(app_client):
@pytest.mark.asyncio
async def test_hook_prepare_jinja2_environment(app_client):
app_client.ds._HELLO = "HI"
template = app_client.ds.jinja_env.from_string(
"Hello there, {{ a|format_numeric }}", {"a": 3412341}
"Hello there, {{ a|format_numeric }}, {{ a|to_hello }}", {"a": 3412341}
)
rendered = await app_client.ds.render_template(template)
assert "Hello there, 3,412,341" == rendered
assert "Hello there, 3,412,341, HI" == rendered
def test_hook_publish_subcommand():