mirror of
https://github.com/simonw/datasette.git
synced 2025-12-10 16:51:24 +01:00
Updated docs
This commit is contained in:
parent
7eb2be41df
commit
9b381458ea
1 changed files with 17 additions and 9 deletions
|
|
@ -629,7 +629,9 @@ Function that returns a dictionary
|
||||||
If you return a function it will be executed. If it returns a dictionary those values will will be merged into the template context.
|
If you return a function it will be executed. If it returns a dictionary those values will will be merged into the template context.
|
||||||
|
|
||||||
Function that returns an awaitable function that returns a dictionary
|
Function that returns an awaitable function that returns a dictionary
|
||||||
You can also return a function which returns an awaitable function which returns a dictionary. This means you can execute additional SQL queries using ``datasette.execute()``.
|
You can also return a function which returns an awaitable function which returns a dictionary.
|
||||||
|
|
||||||
|
Datasette runs Jinja2 in `async mode <https://jinja.palletsprojects.com/en/2.10.x/api/#async-support>`__, which means you can add awaitable functions to the template scope and they will be automatically awaited when they are rendered by the template.
|
||||||
|
|
||||||
Here's an example plugin that returns an authentication object from the ASGI scope:
|
Here's an example plugin that returns an authentication object from the ASGI scope:
|
||||||
|
|
||||||
|
|
@ -641,20 +643,26 @@ Here's an example plugin that returns an authentication object from the ASGI sco
|
||||||
"auth": request.scope.get("auth")
|
"auth": request.scope.get("auth")
|
||||||
}
|
}
|
||||||
|
|
||||||
And here's an example which returns the current version of SQLite:
|
And here's an example which adds a ``query_database(sql)`` function which executes a SQL statement and returns the first column of the row:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
|
|
||||||
@hookimpl
|
@hookimpl
|
||||||
def extra_template_vars(datasette):
|
def extra_template_vars(datasette):
|
||||||
async def inner():
|
|
||||||
|
async def query_database(sql):
|
||||||
first_db = list(datasette.databases.keys())[0]
|
first_db = list(datasette.databases.keys())[0]
|
||||||
return {
|
return (
|
||||||
"sqlite_version": (
|
await datasette.execute(first_db, sql)
|
||||||
await datasette.execute(first_db, "select sqlite_version()")
|
).rows[0][0]
|
||||||
).rows[0][0]
|
|
||||||
}
|
return {
|
||||||
return inner
|
"query_database": query_database,
|
||||||
|
}
|
||||||
|
|
||||||
|
You can then use the new function in a template like so::
|
||||||
|
|
||||||
|
{{ query_database("select sqlite_version()") }}
|
||||||
|
|
||||||
.. _plugin_register_output_renderer:
|
.. _plugin_register_output_renderer:
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue