Template context¶
This page documents the variables that are available to custom templates for each of Datasette's core pages. See Custom templates for how to provide your own templates.
The variables documented here are a stable contract: custom templates that use them will continue to work across Datasette releases, up until the next major version (Datasette 2.0). Anything present in the template context but not documented on this page is not part of that contract and may change or be removed in any release.
You can inspect the full context for any page by starting Datasette with
--setting template_debug 1 and adding ?_context=1 to the page URL.
Base context¶
These variables are available on every page rendered by Datasette, including pages rendered by plugins that use datasette.render_template(). Plugins can add additional variables using the extra_template_vars(template, database, table, columns, view_name, request, datasette) hook.
requestThe current Request object, or None. Common properties include
request.path,request.args,request.actor,request.url_varsandrequest.host.crumb_itemsAsync function returning breadcrumb navigation items for the current page. Call it with
request=requestplus optionaldatabase=andtable=arguments; it returns a list of{"href": url, "label": label}dictionaries.urlsObject with methods for constructing URLs within Datasette. Common methods include
urls.instance(),urls.database(database),urls.table(database, table),urls.query(database, query),urls.row(database, table, row_path)andurls.static(path)- see datasette.urls.actorThe currently authenticated actor dictionary, or None. Actors usually include an
idkey and may include any other keys supplied by authentication plugins.menu_linksAsync function returning links for the Datasette application menu, including links added by plugins. Each item is a link dictionary with
hrefandlabelkeys. See menu_links(datasette, actor, request); for page action menus that can also include JavaScript-backed buttons, see Action hooks.display_actorFunction that accepts an actor dictionary and returns the display string used in the navigation menu.
show_logoutTrue if the logout link should be shown in the navigation menu
zipPython's
zip()builtin, made available to template logicbody_scriptsList of JavaScript snippets contributed by plugins using extra_body_script(template, database, table, columns, view_name, request, datasette). Each item is a dictionary with
scriptcontaining JavaScript source andmoduleindicating whether Datasette will wrap it in<script type="module">; otherwise Datasette wraps it in a regular<script>block.format_bytesFunction that accepts a byte count integer and returns a human-readable string such as
1.2 MB.show_messagesFunction returning any messages set for the current user, clearing them in the process. Returns a list of
(message, type)pairs, wheretypeis one of Datasette'sINFO,WARNINGorERRORconstants.extra_css_urlsList of extra CSS stylesheets to include on the page. Each item is a dictionary with
urland optionalsrikeys, from plugins and configuration.extra_js_urlsList of extra JavaScript URLs to include on the page. Each item is a dictionary with
urlplus optionalsriandmodulekeys, from plugins and configuration.base_urlThe configured base_url setting
datasette_versionThe version of Datasette that is running
Database page¶
The page listing the tables, views and queries in a database, e.g. /fixtures. Rendered using the database.html template.
allow_download-boolBoolean indicating if database download is allowed
allow_execute_sql-boolBoolean indicating if custom SQL can be executed
alternate_url_json-strURL for the alternate JSON version of this page
attached_databases-listList of names of databases attached to this SQLite connection. This is only populated for the special
/_memorydatabase when Datasette is started with--crossdbfor Cross-database queries.database-strThe name of the database
database_actions-callableAsync callable returning action items for the database menu. Each item is either a link with
href,labeland optionaldescriptionkeys, or a button withtype: "button",label, optionaldescriptionand optionalattrs. See Action hooks and database_actions(datasette, actor, database, request).database_color-strThe color assigned to the database
database_page_data-dictJSON data used by JavaScript on the database page. Currently
{}or{"createTable": {...}}wherecreateTableincludespath,foreignKeyTargetsPath,databaseName,columnTypes,defaultExpressionsand optionalcustomColumnTypes.editable-boolBoolean indicating if the database is editable
hidden_count-intCount of hidden tables
metadata-dictMetadata dictionary for the database, such as
title,description,licenseandsourcevalues from Datasette metadata.path-strThe URL path to this database
private-boolBoolean indicating if this is a private database
queries-list[StoredQuery]List of
StoredQueryobjects. Each has attributes includingname,sql,title,description,description_html,hide_sql,fragment,parameters,is_writeandprivate.queries_count-intCount of visible stored queries
queries_more-boolBoolean indicating if more stored queries are available
select_templates-listList of template names that were considered for this page, with the selected template prefixed by
*.show_hidden-strValue of _show_hidden query parameter
size-intThe size of the database in bytes
table_columns-dictDictionary mapping table names to lists of column names, used to power SQL autocomplete.
tables-list[DatabaseTable]List of
DatabaseTableobjects describing tables in the database. Each item hasname,columns,primary_keys,count,count_truncated,hidden,fts_table,foreign_keysandprivateattributes.count_truncatedis true ifcountis a capped lower bound rather than an exact total.top_database-callableAsync callable that renders the
top_databaseplugin slot for this database and returns HTML.views-list[DatabaseViewInfo]List of
DatabaseViewInfoobjects describing SQLite views in the database. Each item hasnameandprivateattributes.
Query page¶
The page for arbitrary SQL queries (/database/-/query?sql=...) and stored queries (/database/query-name). Rendered using the query.html template.
allow_execute_sql-boolBoolean indicating if custom SQL can be executed
alternate_url_json-strURL for alternate JSON version of this page
columns-listList of result column names in the order they appear in
display_rowsandrows.database-strThe name of the database being queried
database_color-strThe color of the database
db_is_immutable-boolBoolean indicating if this database is immutable
display_rows-listList of result rows formatted for HTML display. Each row is a list of rendered cell values in the same order as
columns.edit_sql_url-strURL to edit the SQL for a stored query
editable-boolBoolean indicating if the SQL can be edited
error-strAny query error message
hide_sql-boolBoolean indicating if the SQL should be hidden
metadata-dictMetadata dictionary for the database or stored query. Stored query metadata may include options such as
hide_sql,on_success_messageandon_error_redirect.named_parameter_values-dictDictionary of named SQL parameter values, keyed by parameter name without the leading
:.private-boolBoolean indicating if this is a private database
query-dictDictionary describing the SQL query being executed, with
sqlandparamskeys.query_actions-callableAsync callable returning action items for the query menu. Each item is either a link with
href,labeland optionaldescriptionkeys, or a button withtype: "button",label, optionaldescriptionand optionalattrs. See Action hooks and query_actions(datasette, actor, database, query_name, request, sql, params).renderers-dictDictionary mapping output format names such as
jsonto URLs for this query in that format.save_query_url-strURL to save the current arbitrary SQL as a query
select_templates-listList of template names that were considered for this page, with the selected template prefixed by
*.show_hide_hidden-strRendered hidden
<input>HTML preserving the current_hide_sqlor_show_sqlstate.show_hide_link-strThe URL to toggle showing/hiding the SQL
show_hide_text-strThe text for the show/hide SQL link
stored_query-strThe name of the stored query if this is a stored query
stored_query_write-boolBoolean indicating if this is a stored query that allows writes
table_columns-dictDictionary mapping table names to lists of column names, used to power SQL autocomplete.
tables-list[DatabaseTable]List of
DatabaseTableobjects describing tables in the database. Each item hasname,columns,primary_keys,count,count_truncated,hidden,fts_table,foreign_keysandprivateattributes.count_truncatedis true ifcountis a capped lower bound rather than an exact total.top_query-callableAsync callable that renders the
top_queryplugin slot for this query and returns HTML.top_stored_query-callableAsync callable that renders the
top_stored_queryplugin slot for stored queries and returns HTML.url_csv-strURL for CSV export
Table page¶
The page showing the rows in a table or SQL view, e.g. /fixtures/facetable. Rendered using the table.html template.
Many of these keys are shared with the JSON API for this page.
actions-callableAsync callable returning table or view actions made available by core and plugin hooks. Each item is either a link with
href,labeland optionaldescriptionkeys, or a button withtype: "button",label, optionaldescriptionand optionalattrs. See Action hooks, table_actions(datasette, actor, database, table, request) and view_actions(datasette, actor, database, view, request).all_columns-listList of all column names in the table, regardless of
_col=or_nocol=filtering.allow_execute_sql-boolTrue if the current actor can execute custom SQL against this database
alternate_url_json-strURL for the JSON version of this page
append_querystring-callableFunction
append_querystring(url, querystring)that appends additional query string arguments to a URL, using?or&as appropriate.columns-listList of column names returned by this table, row or query.
count-intTotal count of rows matching these filters
count_sql-strSQL query string used to calculate the total count for the current table view, including active filters.
count_truncated-boolTrue if
countis a capped lower bound rather than an exact total, because Datasette stopped counting after its configured row-count limit.custom_table_templates-listList of custom template names considered for rendering table rows, in lookup order.
database-strDatabase name
database_color-strColor assigned to the database
datasette_allow_facet-strThe string "true" or "false" reflecting the allow_facet setting
display_columns-listColumn metadata used by the HTML table display. Each item includes
name,sortable,is_pk,type,notnull,description,column_typeandcolumn_type_configkeys.display_rows-listRows formatted for the HTML table display. Each row is iterable and contains cell dictionaries with
column,value,rawandvalue_typekeys; table pages may also providepk_path,row_pathandrow_labelattributes on each row object.expandable_columns-listList of foreign key columns that can be expanded with labels. Each item is a
(foreign_key, label_column)pair whereforeign_keyis the SQLite foreign key dictionary andlabel_columnis the label column in the referenced table, orNone.extra_wheres_for_ui-listExtra where clauses from
?_where=for display in the UI. Each item hastextfor the SQL fragment andremove_urlfor a URL that removes that fragment.facet_results-dictResults of facets calculated against this data. A dictionary with
resultsandtimed_outkeys:resultsmaps facet names to facet dictionaries withname,type,resultsand URL keys, and each facet result item includesvalue,label,countandtoggle_url.facets_timed_out-listList of names of facet calculations that exceeded the facet time limit.
filter_columns-listList of column names offered by the filter interface, including currently displayed columns and any hidden columns that can still be filtered.
filters-FiltersFiltersobject used by the HTML table interface. Useful methods includefilters.human_description_en(); this is not JSON serializable.fix_path-callableFunction that applies the configured
base_urlprefix to a path.form_hidden_args-listList of
(name, value)pairs for hidden form fields used by the HTML table interface to preserve current query string options.human_description_en-strHuman-readable description of the filters
is_sortable-boolTrue if any of the displayed columns can be used to sort
is_view-boolWhether this resource is a view instead of a table
metadata-dictMetadata dictionary for the table, database or stored query. Table and row metadata include a
columnsdictionary mapping column names to descriptions; stored query metadata returns the stored query configuration.next-strPagination token for the next page, or None
next_url-strFull URL for the next page of results
ok-boolTrue if the data for this page was retrieved without errors
path_with_replaced_args-callableFunction for building the current path with modified query string arguments. Pass the current
requestand a dictionary of argument names to replacement values, usingNoneto remove an argument.primary_keys-listList of primary key column names for this table, or an empty list if the table has no explicit primary key.
private-boolWhether this resource is private to the current actor
query-dictDetails of the underlying SQL query as a dictionary with
sqlandparamskeys.query_ms-floatTime taken by the SQL queries for this page, in milliseconds
renderers-dictDictionary mapping output format names such as
jsonor plugin-provided renderer names to URLs for this data in that format.rows-listThe rows for this page, as a list of dictionaries mapping column name to raw value.
select_templates-listList of template names that were considered for this page, with the selected template prefixed by
*.set_column_type_ui-dictInformation needed to build an interface for assigning column types, or
Noneif unavailable. When present it haspathandcolumnskeys;columnsmaps column names tocurrentandoptionsvalues.settings-dictDictionary of Datasette's current settings, keyed by setting name.
sort-strColumn the page is sorted by, or None
sort_desc-strColumn the page is sorted by in descending order, or None
sorted_facet_results-listFacet result dictionaries sorted for display. Each item has the same shape as an entry from
facet_results['results'].suggested_facets-listSuggestions for facets that might return interesting results. Each item is a dictionary with
nameandtoggle_urlkeys, and may include extra keys such astypeorlabeldepending on the facet class.supports_search-boolTrue if this table has full-text search configured
table-strTable name
table_alter_ui-dictInformation needed to enable the alter table UI, or
Noneif altering this table is not available to the current actor. When present it haspath,tableName,columns,primaryKeys,columnTypes,defaultExpressionsandforeignKeyTargetsPathkeys, plus optionalcustomColumnTypesanddropPathkeys.table_definition-strSQL definition for this table
table_insert_ui-dictInformation needed to enable the row insertion UI, or
Noneif row insertion is not available to the current actor. When present it haspath,tableName,columnsandprimaryKeyskeys; each column includesname,sqlite_type,notnull,default,has_default,is_pk,value_kindandcolumn_typekeys.table_page_data-dictJSON data used by JavaScript on the table page. Includes
database,tableandtableUrl, plus optionalforeignKeysmapping column names to autocomplete URLs, optionalinsertRowdata and optionalalterTabledata.top_table-callableAsync callable that renders the
top_tableplugin slot for this table or view and returns HTML.url_csv-strURL for the CSV export of this page
url_csv_hidden_args-listList of
(name, value)pairs for hidden form fields used by the CSV export form, preserving current filters while forcing_size=max.url_csv_path-strPath portion of the CSV export URL
view_definition-strSQL definition for this view
Row page¶
The page showing an individual row, e.g. /fixtures/facetable/1. Rendered using the row.html template.
Many of these keys are shared with the JSON API for this page.
alternate_url_json-strURL for the JSON version of this page
columns-listList of column names returned by this table, row or query.
custom_table_templates-listCustom template names that were considered for displaying this row's table, in lookup order.
database-strDatabase name
database_color-strColor assigned to the database
display_columns-listColumn metadata used by the HTML table display. Each item includes
name,sortable,is_pk,type,notnull,description,column_typeandcolumn_type_configkeys.display_rows-listRows formatted for the HTML table display. Each row is iterable and contains cell dictionaries with
column,value,rawandvalue_typekeys.foreign_key_tables-listList of tables that link to this row using foreign keys. Each item includes the foreign key fields plus
countfor matching rows andlinkfor the filtered table URL.metadata-dictMetadata dictionary for the table, database or stored query. Table and row metadata include a
columnsdictionary mapping column names to descriptions; stored query metadata returns the stored query configuration.ok-boolTrue if the data for this page was retrieved without errors
primary_key_values-listValues of the primary keys for this row, from the URL
primary_keys-listList of primary key column names for this table, or an empty list if the table has no explicit primary key.
private-boolWhether this resource is private to the current actor
query_ms-floatTime taken by the SQL queries for this page, in milliseconds
renderers-dictDictionary mapping output format names such as
jsonto URLs for this row in that format.row_actions-listRow actions made available by core and plugin hooks. Each item is either a link with
href,labeland optionaldescriptionkeys, or a button withtype: "button",label, optionaldescriptionand optionalattrs. See Action hooks and row_actions(datasette, actor, request, database, table, row).row_mutation_ui-boolTrue if the row edit/delete JavaScript UI should be enabled
rows-listA single-item list containing this row as a dictionary mapping column name to raw value.
select_templates-listList of template names that were considered for this page, with the selected template prefixed by
*.settings-dictDictionary of Datasette's current settings, keyed by setting name.
table-strTable name
table_page_data-dictJSON data used by JavaScript on the row page. Includes
database,tableandtableUrl, plus optionalforeignKeysmapping column names to autocomplete URLs.top_row-callableAsync callable that renders the
top_rowplugin slot for this row and returns HTML.url_csv-strURL for the CSV export of this page
url_csv_hidden_args-listList of
(name, value)pairs for hidden form fields used by the CSV export form, preserving current options while forcing_size=max.url_csv_path-strPath portion of the CSV export URL