Debian Codegraph @

docs/custom_templates.rst

raw
1 .. _customization:
2
3 Custom pages and templates
4 ==========================
5
6 Datasette provides a number of ways of customizing the way data is displayed.
7
8 .. _customization_css_and_javascript:
9
10 Custom CSS and JavaScript
11 -------------------------
12
13 When you launch Datasette, you can specify a custom metadata file like this::
14
15 datasette mydb.db --metadata metadata.json
16
17 Your ``metadata.json`` file can include links that look like this:
18
19 .. code-block:: json
20
21 {
22 "extra_css_urls": [
23 "https://simonwillison.net/static/css/all.bf8cd891642c.css"
24 ],
25 "extra_js_urls": [
26 "https://code.jquery.com/jquery-3.2.1.slim.min.js"
27 ]
28 }
29
30 The extra CSS and JavaScript files will be linked in the ``<head>`` of every page:
31
32 .. code-block:: html
33
34 <link rel="stylesheet" href="https://simonwillison.net/static/css/all.bf8cd891642c.css">
35 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
36
37 You can also specify a SRI (subresource integrity hash) for these assets:
38
39 .. code-block:: json
40
41 {
42 "extra_css_urls": [
43 {
44 "url": "https://simonwillison.net/static/css/all.bf8cd891642c.css",
45 "sri": "sha384-9qIZekWUyjCyDIf2YK1FRoKiPJq4PHt6tp/ulnuuyRBvazd0hG7pWbE99zvwSznI"
46 }
47 ],
48 "extra_js_urls": [
49 {
50 "url": "https://code.jquery.com/jquery-3.2.1.slim.min.js",
51 "sri": "sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
52 }
53 ]
54 }
55
56 This will produce:
57
58 .. code-block:: html
59
60 <link rel="stylesheet" href="https://simonwillison.net/static/css/all.bf8cd891642c.css"
61 integrity="sha384-9qIZekWUyjCyDIf2YK1FRoKiPJq4PHt6tp/ulnuuyRBvazd0hG7pWbE99zvwSznI"
62 crossorigin="anonymous">
63 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
64 integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
65 crossorigin="anonymous"></script>
66
67 Modern browsers will only execute the stylesheet or JavaScript if the SRI hash
68 matches the content served. You can generate hashes using `www.srihash.org <https://www.srihash.org/>`_
69
70 Items in ``"extra_js_urls"`` can specify ``"module": true`` if they reference JavaScript that uses `JavaScript modules <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules>`__. This configuration:
71
72 .. code-block:: json
73
74 {
75 "extra_js_urls": [
76 {
77 "url": "https://example.datasette.io/module.js",
78 "module": true
79 }
80 ]
81 }
82
83 Will produce this HTML:
84
85 .. code-block:: html
86
87 <script type="module" src="https://example.datasette.io/module.js"></script>
88
89 CSS classes on the <body>
90 ~~~~~~~~~~~~~~~~~~~~~~~~~
91
92 Every default template includes CSS classes in the body designed to support
93 custom styling.
94
95 The index template (the top level page at ``/``) gets this:
96
97 .. code-block:: html
98
99 <body class="index">
100
101 The database template (``/dbname``) gets this:
102
103 .. code-block:: html
104
105 <body class="db db-dbname">
106
107 The custom SQL template (``/dbname?sql=...``) gets this:
108
109 .. code-block:: html
110
111 <body class="query db-dbname">
112
113 A canned query template (``/dbname/queryname``) gets this:
114
115 .. code-block:: html
116
117 <body class="query db-dbname query-queryname">
118
119 The table template (``/dbname/tablename``) gets:
120
121 .. code-block:: html
122
123 <body class="table db-dbname table-tablename">
124
125 The row template (``/dbname/tablename/rowid``) gets:
126
127 .. code-block:: html
128
129 <body class="row db-dbname table-tablename">
130
131 The ``db-x`` and ``table-x`` classes use the database or table names themselves if
132 they are valid CSS identifiers. If they aren't, we strip any invalid
133 characters out and append a 6 character md5 digest of the original name, in
134 order to ensure that multiple tables which resolve to the same stripped
135 character version still have different CSS classes.
136
137 Some examples::
138
139 "simple" => "simple"
140 "MixedCase" => "MixedCase"
141 "-no-leading-hyphens" => "no-leading-hyphens-65bea6"
142 "_no-leading-underscores" => "no-leading-underscores-b921bc"
143 "no spaces" => "no-spaces-7088d7"
144 "-" => "336d5e"
145 "no $ characters" => "no--characters-59e024"
146
147 ``<td>`` and ``<th>`` elements also get custom CSS classes reflecting the
148 database column they are representing, for example:
149
150 .. code-block:: html
151
152 <table>
153 <thead>
154 <tr>
155 <th class="col-id" scope="col">id</th>
156 <th class="col-name" scope="col">name</th>
157 </tr>
158 </thead>
159 <tbody>
160 <tr>
161 <td class="col-id"><a href="...">1</a></td>
162 <td class="col-name">SMITH</td>
163 </tr>
164 </tbody>
165 </table>
166
167 .. _customization_static_files:
168
169 Serving static files
170 ~~~~~~~~~~~~~~~~~~~~
171
172 Datasette can serve static files for you, using the ``--static`` option.
173 Consider the following directory structure::
174
175 metadata.json
176 static-files/styles.css
177 static-files/app.js
178
179 You can start Datasette using ``--static assets:static-files/`` to serve those
180 files from the ``/assets/`` mount point::
181
182 $ datasette -m metadata.json --static assets:static-files/ --memory
183
184 The following URLs will now serve the content from those CSS and JS files::
185
186 http://localhost:8001/assets/styles.css
187 http://localhost:8001/assets/app.js
188
189 You can reference those files from ``metadata.json`` like so:
190
191 .. code-block:: json
192
193 {
194 "extra_css_urls": [
195 "/assets/styles.css"
196 ],
197 "extra_js_urls": [
198 "/assets/app.js"
199 ]
200 }
201
202 Publishing static assets
203 ~~~~~~~~~~~~~~~~~~~~~~~~
204
205 The :ref:`cli_publish` command can be used to publish your static assets,
206 using the same syntax as above::
207
208 $ datasette publish cloudrun mydb.db --static assets:static-files/
209
210 This will upload the contents of the ``static-files/`` directory as part of the
211 deployment, and configure Datasette to correctly serve the assets from ``/assets/``.
212
213 .. _customization_custom_templates:
214
215 Custom templates
216 ----------------
217
218 By default, Datasette uses default templates that ship with the package.
219
220 You can over-ride these templates by specifying a custom ``--template-dir`` like
221 this::
222
223 datasette mydb.db --template-dir=mytemplates/
224
225 Datasette will now first look for templates in that directory, and fall back on
226 the defaults if no matches are found.
227
228 It is also possible to over-ride templates on a per-database, per-row or per-
229 table basis.
230
231 The lookup rules Datasette uses are as follows::
232
233 Index page (/):
234 index.html
235
236 Database page (/mydatabase):
237 database-mydatabase.html
238 database.html
239
240 Custom query page (/mydatabase?sql=...):
241 query-mydatabase.html
242 query.html
243
244 Canned query page (/mydatabase/canned-query):
245 query-mydatabase-canned-query.html
246 query-mydatabase.html
247 query.html
248
249 Table page (/mydatabase/mytable):
250 table-mydatabase-mytable.html
251 table.html
252
253 Row page (/mydatabase/mytable/id):
254 row-mydatabase-mytable.html
255 row.html
256
257 Table of rows and columns include on table page:
258 _table-table-mydatabase-mytable.html
259 _table-mydatabase-mytable.html
260 _table.html
261
262 Table of rows and columns include on row page:
263 _table-row-mydatabase-mytable.html
264 _table-mydatabase-mytable.html
265 _table.html
266
267 If a table name has spaces or other unexpected characters in it, the template
268 filename will follow the same rules as our custom ``<body>`` CSS classes - for
269 example, a table called "Food Trucks" will attempt to load the following
270 templates::
271
272 table-mydatabase-Food-Trucks-399138.html
273 table.html
274
275 You can find out which templates were considered for a specific page by viewing
276 source on that page and looking for an HTML comment at the bottom. The comment
277 will look something like this::
278
279 <!-- Templates considered: *query-mydb-tz.html, query-mydb.html, query.html -->
280
281 This example is from the canned query page for a query called "tz" in the
282 database called "mydb". The asterisk shows which template was selected - so in
283 this case, Datasette found a template file called ``query-mydb-tz.html`` and
284 used that - but if that template had not been found, it would have tried for
285 ``query-mydb.html`` or the default ``query.html``.
286
287 It is possible to extend the default templates using Jinja template
288 inheritance. If you want to customize EVERY row template with some additional
289 content you can do so by creating a ``row.html`` template like this:
290
291 .. code-block:: jinja
292
293 {% extends "default:row.html" %}
294
295 {% block content %}
296 <h1>EXTRA HTML AT THE TOP OF THE CONTENT BLOCK</h1>
297 <p>This line renders the original block:</p>
298 {{ super() }}
299 {% endblock %}
300
301 Note the ``default:row.html`` template name, which ensures Jinja will inherit
302 from the default template.
303
304 The ``_table.html`` template is included by both the row and the table pages,
305 and a list of rows. The default ``_table.html`` template renders them as an
306 HTML template and `can be seen here <https://github.com/simonw/datasette/blob/main/datasette/templates/_table.html>`_.
307
308 You can provide a custom template that applies to all of your databases and
309 tables, or you can provide custom templates for specific tables using the
310 template naming scheme described above.
311
312 If you want to present your data in a format other than an HTML table, you
313 can do so by looping through ``display_rows`` in your own ``_table.html``
314 template. You can use ``{{ row["column_name"] }}`` to output the raw value
315 of a specific column.
316
317 If you want to output the rendered HTML version of a column, including any
318 links to foreign keys, you can use ``{{ row.display("column_name") }}``.
319
320 Here is an example of a custom ``_table.html`` template:
321
322 .. code-block:: jinja
323
324 {% for row in display_rows %}
325 <div>
326 <h2>{{ row["title"] }}</h2>
327 <p>{{ row["description"] }}<lp>
328 <p>Category: {{ row.display("category_id") }}</p>
329 </div>
330 {% endfor %}
331
332 .. _custom_pages:
333
334 Custom pages
335 ------------
336
337 You can add templated pages to your Datasette instance by creating HTML files in a ``pages`` directory within your ``templates`` directory.
338
339 For example, to add a custom page that is served at ``http://localhost/about`` you would create a file in ``templates/pages/about.html``, then start Datasette like this::
340
341 $ datasette mydb.db --template-dir=templates/
342
343 You can nest directories within pages to create a nested structure. To create a ``http://localhost:8001/about/map`` page you would create ``templates/pages/about/map.html``.
344
345 .. _custom_pages_parameters:
346
347 Path parameters for pages
348 ~~~~~~~~~~~~~~~~~~~~~~~~~
349
350 You can define custom pages that match multiple paths by creating files with ``{variable}`` definitions in their filenames.
351
352 For example, to capture any request to a URL matching ``/about/*``, you would create a template in the following location::
353
354 templates/pages/about/{slug}.html
355
356 A hit to ``/about/news`` would render that template and pass in a variable called ``slug`` with a value of ``"news"``.
357
358 If you use this mechanism don't forget to return a 404 if the referenced content could not be found. You can do this using ``{{ raise_404() }}`` described below.
359
360 Templates defined using custom page routes work particularly well with the ``sql()`` template function from `datasette-template-sql <https://github.com/simonw/datasette-template-sql>`__ or the ``graphql()`` template function from `datasette-graphql <https://github.com/simonw/datasette-graphql#the-graphql-template-function>`__.
361
362 .. _custom_pages_headers:
363
364 Custom headers and status codes
365 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
366
367 Custom pages default to being served with a content-type of ``text/html; charset=utf-8`` and a ``200`` status code. You can change these by calling a custom function from within your template.
368
369 For example, to serve a custom page with a ``418 I'm a teapot`` HTTP status code, create a file in ``pages/teapot.html`` containing the following:
370
371 .. code-block:: jinja
372
373 {{ custom_status(418) }}
374 <html>
375 <head><title>Teapot</title></head>
376 <body>
377 I'm a teapot
378 </body>
379 </html>
380
381 To serve a custom HTTP header, add a ``custom_header(name, value)`` function call. For example:
382
383 .. code-block:: jinja
384
385 {{ custom_status(418) }}
386 {{ custom_header("x-teapot", "I am") }}
387 <html>
388 <head><title>Teapot</title></head>
389 <body>
390 I'm a teapot
391 </body>
392 </html>
393
394 You can verify this is working using ``curl`` like this::
395
396 $ curl -I 'http://127.0.0.1:8001/teapot'
397 HTTP/1.1 418
398 date: Sun, 26 Apr 2020 18:38:30 GMT
399 server: uvicorn
400 x-teapot: I am
401 content-type: text/html; charset=utf-8
402
403 .. _custom_pages_404:
404
405 Returning 404s
406 ~~~~~~~~~~~~~~
407
408 To indicate that content could not be found and display the default 404 page you can use the ``raise_404(message)`` function:
409
410 .. code-block:: jinja
411
412 {% if not rows %}
413 {{ raise_404("Content not found") }}
414 {% endif %}
415
416 If you call ``raise_404()`` the other content in your template will be ignored.
417
418 .. _custom_pages_redirects:
419
420 Custom redirects
421 ~~~~~~~~~~~~~~~~
422
423 You can use the ``custom_redirect(location)`` function to redirect users to another page, for example in a file called ``pages/datasette.html``:
424
425 .. code-block:: jinja
426
427 {{ custom_redirect("https://github.com/simonw/datasette") }}
428
429 Now requests to ``http://localhost:8001/datasette`` will result in a redirect.
430
431 These redirects are served with a ``302 Found`` status code by default. You can send a ``301 Moved Permanently`` code by passing ``301`` as the second argument to the function:
432
433 .. code-block:: jinja
434
435 {{ custom_redirect("https://github.com/simonw/datasette", 301) }}
436
437 .. _custom_pages_errors:
438
439 Custom error pages
440 ------------------
441
442 Datasette returns an error page if an unexpected error occurs, access is forbidden or content cannot be found.
443
444 You can customize the response returned for these errors by providing a custom error page template.
445
446 Content not found errors use a ``404.html`` template. Access denied errors use ``403.html``. Invalid input errors use ``400.html``. Unexpected errors of other kinds use ``500.html``.
447
448 If a template for the specific error code is not found a template called ``error.html`` will be used instead. If you do not provide that template Datasette's `default error.html template <https://github.com/simonw/datasette/blob/main/datasette/templates/error.html>`__ will be used.
449
450 The error template will be passed the following context:
451
452 ``status`` - integer
453 The integer HTTP status code, e.g. 404, 500, 403, 400.
454
455 ``error`` - string
456 Details of the specific error, usually a full sentence.
457
458 ``title`` - string or None
459 A title for the page representing the class of error. This is often ``None`` for errors that do not provide a title separate from their ``error`` message.