Docs for datasette.urls, closes #904

This commit is contained in:
Simon Willison 2020-10-19 17:51:39 -07:00
commit 5aacc021b5
2 changed files with 47 additions and 0 deletions

View file

@ -365,6 +365,34 @@ It offers the following methods:
For documentation on available ``**kwargs`` options and the shape of the HTTPX Response object refer to the `HTTPX Async documentation <https://www.python-httpx.org/async/>`__.
.. _internals_datasette_urls:
datasette.urls
--------------
The ``datasette.urls`` object contains methods for building URLs to pages within Datasette. Plugins should use this to link to pages, since these methods take into account any :ref:`config_base_url` configuration setting that might be in effect.
``datasette.urls.instance()``
Returns the URL to the Datasette instance root page. This is usually ``"/"``
``datasette.urls.database(database_name)``
Returns the URL to a database page, for example ``"/fixtures"``
``datasette.urls.table(database_name, table_name)``
Returns the URL to a table page, for example ``"/fixtures/facetable"``
``datasette.urls.query(database_name, query_name)``
Returns the URL to a query page, for example ``"/fixtures/pragma_cache_size"``
These functions can be accessed via the ``{{ urls }}`` object in Datasette templates, for example:
.. code-block:: jinja
<a href="{{ urls.instance() }}">Homepage</a>
<a href="{{ urls.database("fixtures") }}">Fixtures database</a>
<a href="{{ urls.table("fixtures", "facetable") }}">facetable table</a>
<a href="{{ urls.query("fixtures", "pragma_cache_size") }}">pragma_cache_size query</a>
.. _internals_database:
Database class

View file

@ -175,3 +175,22 @@ The plugin configuration could also be set at the top level of ``metadata.json``
}
Now that ``datasette-cluster-map`` plugin configuration will apply to every table in every database.
.. _writing_plugins_building_urls:
Building URLs within plugins
----------------------------
Plugins that define their own custom user interface elements may need to link to other pages within Datasette.
This can be a bit tricky if the Datasette instance is using the :ref:`config_base_url` configuration setting to run behind a proxy, since that can cause Datasette's URLs to include an additional prefix.
The ``datasette.urls`` object provides internal methods for correctly generating URLs to different pages within Datasette, taking any ``base_url`` configuration into account.
This object is exposed in templates as the ``urls`` variable, which can be used like this:
.. code-block:: jinja
Back to the <a href="{{ urls.instance() }}">Homepage</a>
see :ref:`internals_datasette_urls` for full details on this object.