Debian Codegraph @

doc/development/html_themes/index.rst

raw
1 .. _extension-html-theme:
2
3 HTML theme development
4 ======================
5
6 .. versionadded:: 0.6
7
8 .. note::
9
10 This document provides information about creating your own theme. If you
11 simply wish to use a pre-existing HTML themes, refer to
12 :doc:`/usage/theming`.
13
14 Sphinx supports changing the appearance of its HTML output via *themes*. A
15 theme is a collection of HTML templates, stylesheet(s) and other static files.
16 Additionally, it has a configuration file which specifies from which theme to
17 inherit, which highlighting style to use, and what options exist for customizing
18 the theme's look and feel.
19
20 Themes are meant to be project-unaware, so they can be used for different
21 projects without change.
22
23 .. note::
24
25 See :ref:`dev-extensions` for more information that may
26 be helpful in developing themes.
27
28
29 Creating themes
30 ---------------
31
32 Themes take the form of either a directory or a zipfile (whose name is the
33 theme name), containing the following:
34
35 * Either a :file:`theme.toml` file (preferred) or a :file:`theme.conf` file.
36 * HTML templates, if needed.
37 * A ``static/`` directory containing any static files that will be copied to the
38 output static directory on build. These can be images, styles, script files.
39
40 Theme configuration (``theme.toml``)
41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42
43 The :file:`theme.toml` file is a TOML_ document,
44 containing two tables: ``[theme]`` and ``[options]``.
45
46 The ``[theme]`` table defines the theme's settings:
47
48 * **inherit** (string): The name of the base theme from which to inherit
49 settings, options, templates, and static files.
50 All static files from theme 'ancestors' will be used.
51 The theme will use all options defined in inherited themes.
52 Finally, inherited themes will be used to locate missing templates
53 (for example, if ``"basic"`` is used as the base theme, most templates will
54 already be defined).
55
56 If set to ``"none"``, the theme will not inherit from any other theme.
57 Inheritance is recursive, forming a chain of inherited themes
58 (e.g. ``default`` -> ``classic`` -> ``basic`` -> ``none``).
59
60 * **stylesheets** (list of strings): A list of CSS filenames which will be
61 included in generated HTML header.
62 Setting the :confval:`html_style` config value will override this setting.
63
64 Other mechanisms for including multiple stylesheets include ``@import`` in CSS
65 or using a custom HTML template with appropriate ``<link rel="stylesheet">`` tags.
66
67 * **sidebars** (list of strings): A list of sidebar templates.
68 This can be overridden by the user via the :confval:`html_sidebars` config value.
69
70 * **pygments_style** (table): A TOML table defining the names of Pygments styles
71 to use for highlighting syntax.
72 The table has two recognised keys: ``default`` and ``dark``.
73 The style defined in the ``dark`` key will be used when
74 the CSS media query ``(prefers-color-scheme: dark)`` evaluates to true.
75
76 ``[theme.pygments_style.default]`` can be overridden by the user via the
77 :confval:`pygments_style` config value.
78
79 The ``[options]`` table defines the options for the theme.
80 It is structured such that each key-value pair corresponds to a variable name
81 and the corresponding default value.
82 These options can be overridden by the user in :confval:`html_theme_options`
83 and are accessible from all templates as ``theme_<name>``.
84
85 .. versionadded:: 7.3
86 ``theme.toml`` support.
87
88 .. _TOML: https://toml.io/en/
89
90 Exemplar :file:`theme.toml` file:
91
92 .. code-block:: toml
93
94 [theme]
95 inherit = "basic"
96 stylesheets = [
97 "main-CSS-stylesheet.css",
98 ]
99 sidebars = [
100 "localtoc.html",
101 "relations.html",
102 "sourcelink.html",
103 "searchbox.html",
104 ]
105 # Style names from https://pygments.org/styles/
106 pygments_style = { default = "style_name", dark = "dark_style" }
107
108 [options]
109 variable = "default value"
110
111 Theme configuration (``theme.conf``)
112 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
113
114 The :file:`theme.conf` file is in INI format [1]_ (readable by the standard
115 Python :mod:`configparser` module) and has the following structure:
116
117 .. code-block:: ini
118
119 [theme]
120 inherit = base theme
121 stylesheet = main CSS name
122 pygments_style = stylename
123 sidebars = localtoc.html, relations.html, sourcelink.html, searchbox.html
124
125 [options]
126 variable = default value
127
128 * The **inherit** setting gives the name of a "base theme", or ``none``. The
129 base theme will be used to locate missing templates (most themes will not have
130 to supply most templates if they use ``basic`` as the base theme), its options
131 will be inherited, and all of its static files will be used as well. If you
132 want to also inherit the stylesheet, include it via CSS' ``@import`` in your
133 own.
134
135 * The **stylesheet** setting gives a list of CSS filenames separated commas which
136 will be referenced in the HTML header. You can also use CSS' ``@import``
137 technique to include one from the other, or use a custom HTML template that
138 adds ``<link rel="stylesheet">`` tags as necessary. Setting the
139 :confval:`html_style` config value will override this setting.
140
141 * The **pygments_style** setting gives the name of a Pygments style to use for
142 highlighting. This can be overridden by the user in the
143 :confval:`pygments_style` config value.
144
145 * The **pygments_dark_style** setting gives the name of a Pygments style to use
146 for highlighting when the CSS media query ``(prefers-color-scheme: dark)``
147 evaluates to true. It is injected into the page using
148 :meth:`~sphinx.application.Sphinx.add_css_file`.
149
150 * The **sidebars** setting gives the comma separated list of sidebar templates
151 for constructing sidebars. This can be overridden by the user in the
152 :confval:`html_sidebars` config value.
153
154 * The **options** section contains pairs of variable names and default values.
155 These options can be overridden by the user in :confval:`html_theme_options`
156 and are accessible from all templates as ``theme_<name>``.
157
158 .. versionadded:: 1.7
159 sidebar settings
160
161 .. versionchanged:: 5.1
162
163 The stylesheet setting accepts multiple CSS filenames
164
165 Convert ``theme.conf`` to ``theme.toml``
166 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167
168 INI-style theme configuration files (``theme.conf``) can be converted to TOML
169 via a helper programme distributed with Sphinx.
170 This is intended for one-time use, and may be removed without notice in a future
171 version of Sphinx.
172
173 .. code-block:: console
174
175 $ python -m sphinx.theming conf_to_toml [THEME DIRECTORY PATH]
176
177 The required argument is a path to a directory containing a ``theme.conf`` file.
178 The programme will write a ``theme.toml`` file in the same directory,
179 and will not modify the original ``theme.conf`` file.
180
181 .. versionadded:: 7.3
182
183 .. _distribute-your-theme:
184
185 Distribute your theme as a Python package
186 -----------------------------------------
187
188 As a way to distribute your theme, you can use a Python package. This makes it
189 easier for users to set up your theme.
190
191 To distribute your theme as a Python package, please define an entry point
192 called ``sphinx.html_themes`` in your ``pyproject.toml`` file,
193 and write a ``setup()`` function to register your theme
194 using the :meth:`~sphinx.application.Sphinx.add_html_theme` API:
195
196 .. code-block:: toml
197
198 # pyproject.toml
199
200 [project.entry-points."sphinx.html_themes"]
201 name_of_theme = "your_theme_package"
202
203 .. code-block:: python
204
205 # your_theme_package.py
206 from pathlib import Path
207
208 def setup(app):
209 app.add_html_theme('name_of_theme', Path(__file__).resolve().parent)
210
211 If your theme package contains two or more themes, please call
212 ``add_html_theme()`` twice or more.
213
214 .. versionadded:: 1.2
215 'sphinx_themes' entry_points feature.
216
217 .. deprecated:: 1.6
218 ``sphinx_themes`` entry_points has been deprecated.
219
220 .. versionadded:: 1.6
221 ``sphinx.html_themes`` entry_points feature.
222
223
224 Styling with CSS
225 ----------------
226
227 The :confval:`!stylesheets` setting can be used to add custom CSS files to a theme.
228
229 .. caution::
230
231 The structure of the HTML elements and their classes are currently not a
232 well-defined public API. Please infer them from inspecting the built HTML
233 pages. While we cannot guarantee full stability, they tend to be fairly
234 stable.
235
236 Styling search result entries by category
237 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
238
239 .. versionadded:: 8.0
240
241 .. note::
242
243 The CSS classes named below are generated by Sphinx's standalone search
244 code. If you are using a third-party search provider, such as
245 ReadTheDocs_, to provide search results, then the theming options available
246 may vary.
247
248 .. _ReadTheDocs: https://docs.readthedocs.io/
249
250 The search result items have classes indicating the context in which the
251 search term was found. You can use the CSS selectors:
252
253 - ``ul.search li.kind-index``:
254 For results in an index, such as the glossary
255 - ``ul.search li.kind-object``:
256 For results in source code, like Python function definitions
257 - ``ul.search li.kind-title``:
258 For results found in section headings
259 - ``ul.search li.kind-text``:
260 For results found anywhere else in the documentation text
261
262 As a base for inheritance by other themes, the ``basic`` theme is
263 intentionally minimal and does not define CSS rules using these.
264 Derived themes are encouraged to use these selectors as they see fit.
265 For example, the following stylesheet adds contextual icons to the
266 search result list:
267
268 .. code-block:: css
269
270 ul.search {
271 padding-left: 30px;
272 }
273 ul.search li {
274 padding: 5px 0 5px 10px;
275 list-style-type: "\25A1"; /* Unicode: White Square */
276 }
277 ul.search li.kind-index {
278 list-style-type: "\1F4D1"; /* Unicode: Bookmark Tabs */
279 }
280 ul.search li.kind-object {
281 list-style-type: "\1F4E6"; /* Unicode: Package */
282 }
283 ul.search li.kind-title {
284 list-style-type: "\1F4C4"; /* Unicode: Page Facing Up */
285 }
286 ul.search li.kind-text {
287 list-style-type: "\1F4C4"; /* Unicode: Page Facing Up */
288 }
289
290
291 Templating
292 ----------
293
294 .. toctree::
295 :hidden:
296
297 templating
298
299 The :doc:`guide to templating <templating>` is helpful if you want to write your
300 own templates. What is important to keep in mind is the order in which Sphinx
301 searches for templates:
302
303 * First, in the user's ``templates_path`` directories.
304 * Then, in the selected theme.
305 * Then, in its base theme, its base's base theme, etc.
306
307 When extending a template in the base theme with the same name, use the theme
308 name as an explicit directory: ``{% extends "basic/layout.html" %}``. From a
309 user ``templates_path`` template, you can still use the "exclamation mark"
310 syntax as :ref:`described in the templating document <templating-primer>`.
311
312
313 .. _theming-static-templates:
314
315 Static templates
316 ~~~~~~~~~~~~~~~~
317
318 Since theme options are meant for the user to configure a theme more easily,
319 without having to write a custom stylesheet, it is necessary to be able to
320 template static files as well as HTML files. Therefore, Sphinx supports
321 so-called "static templates", like this:
322
323 If the name of a file in the ``static/`` directory of a theme (or in the user's
324 static path) ends with ``.jinja`` or ``_t``, it will be processed by the
325 template engine. The suffix will be removed from the final file name.
326
327 For example, a theme with a ``static/theme_styles.css.jinja`` file could use
328 templating to put options into the stylesheet.
329 When a documentation project is built with that theme,
330 the output directory will contain a ``_static/theme_styles.css`` file
331 where all template tags have been processed.
332
333 .. versionchanged:: 7.4
334
335 The preferred suffix for static templates is now ``.jinja``, in line with
336 the Jinja project's `recommended file extension`_.
337
338 The ``_t`` file suffix for static templates is now considered 'legacy', and
339 support may eventually be removed.
340
341 If a static template with either a ``_t`` suffix or a ``.jinja`` suffix is
342 detected, it will be processed by the template engine, with the suffix
343 removed from the final file name.
344
345 .. _recommended file extension: https://jinja.palletsprojects.com/en/latest/templates/#template-file-extension
346
347
348 Use custom page metadata in HTML templates
349 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
350
351 Any key / value pairs in :doc:`field lists </usage/restructuredtext/field-lists>`
352 that are placed *before* the page's title will be available to the Jinja
353 template when building the page within the :data:`meta` attribute. For example,
354 if a page had the following text before its first title:
355
356 .. code-block:: rst
357
358 :mykey: My value
359
360 My first title
361 --------------
362
363 Then it could be accessed within a Jinja template like so:
364
365 .. code-block:: jinja
366
367 {%- if meta is mapping %}
368 {{ meta.get("mykey") }}
369 {%- endif %}
370
371 Note the check that ``meta`` is a dictionary ("mapping" in Jinja
372 terminology) to ensure that using it in this way is valid.
373
374
375 Defining custom template functions
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377
378 Sometimes it is useful to define your own function in Python that you wish to
379 then use in a template. For example, if you'd like to insert a template value
380 with logic that depends on the user's configuration in the project, or if you'd
381 like to include non-trivial checks and provide friendly error messages for
382 incorrect configuration in the template.
383
384 To define your own template function, you'll need to define two functions
385 inside your module:
386
387 * A **page context event handler** (or **registration**) function. This is
388 connected to the :class:`.Sphinx` application via an event callback.
389 * A **template function** that you will use in your Jinja template.
390
391 First, define the registration function, which accepts the arguments for
392 :event:`html-page-context`.
393
394 Within the registration function, define the template function that you'd like to
395 use within Jinja. The template function should return a string or Python objects
396 (lists, dictionaries) with strings inside that Jinja uses in the templating process
397
398 .. note::
399
400 The template function will have access to all of the variables that
401 are passed to the registration function.
402
403 At the end of the registration function, add the template function to the
404 Sphinx application's context with ``context['template_func'] = template_func``.
405
406 Finally, in your extension's ``setup()`` function, add your registration
407 function as a callback for :event:`html-page-context`.
408
409 .. code-block:: python
410
411 # The registration function
412 def setup_my_func(app, pagename, templatename, context, doctree):
413 # The template function
414 def my_func(mystring):
415 return "Your string is %s" % mystring
416 # Add it to the page's context
417 context['my_func'] = my_func
418
419 # Your extension's setup function
420 def setup(app):
421 app.connect("html-page-context", setup_my_func)
422
423 Now, you will have access to this function in jinja like so:
424
425 .. code-block:: jinja
426
427 <div>
428 {{ my_func("some string") }}
429 </div>
430
431
432 Add your own static files to the build assets
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
434
435 By default, Sphinx copies static files on the ``static/`` directory of the template
436 directory. However, if your package needs to place static files outside of the
437 ``static/`` directory for some reasons, you need to copy them to the ``_static/``
438 directory of HTML outputs manually at the build via an event hook. Here is an
439 example of code to accomplish this:
440
441 .. code-block:: python
442
443 import shutil
444
445 def copy_custom_files(app, exc):
446 if app.builder.format == 'html' and not exc:
447 static_dir = app.outdir / '_static'
448 shutil.copyfile('path/to/myextension/_static/myjsfile.js', static_dir)
449
450 def setup(app):
451 app.connect('build-finished', copy_custom_files)
452
453
454 Inject JavaScript based on user configuration
455 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
456
457 If your extension makes use of JavaScript, it can be useful to allow users
458 to control its behavior using their Sphinx configuration. However, this can
459 be difficult to do if your JavaScript comes in the form of a static library
460 (which will not be built with Jinja).
461
462 There are two ways to inject variables into the JavaScript space based on user
463 configuration.
464
465 First, you may append ``_t`` to the end of any static files included with your
466 extension. This will cause Sphinx to process these files with the templating
467 engine, allowing you to embed variables and control behavior.
468
469 For example, the following JavaScript structure:
470
471 .. code-block:: none
472
473 mymodule/
474 ├── _static
475 │   └── myjsfile.js_t
476 └── mymodule.py
477
478 Will result in the following static file placed in your HTML's build output:
479
480 .. code-block:: none
481
482 _build/
483 └── html
484 └── _static
485    └── myjsfile.js
486
487 See :ref:`theming-static-templates` for more information.
488
489 Second, you may use the :meth:`.Sphinx.add_js_file` method without pointing it
490 to a file. Normally, this method is used to insert a new JavaScript file
491 into your site. However, if you do *not* pass a file path, but instead pass
492 a string to the "body" argument, then this text will be inserted as JavaScript
493 into your site's head. This allows you to insert variables into your project's
494 JavaScript from Python.
495
496 For example, the following code will read in a user-configured value and then
497 insert this value as a JavaScript variable, which your extension's JavaScript
498 code may use:
499
500 .. code-block:: python
501
502 # This function reads in a variable and inserts it into JavaScript
503 def add_js_variable(app):
504 # This is a configuration that you've specified for users in `conf.py`
505 js_variable = app.config['my_javascript_variable']
506 js_text = "var my_variable = '%s';" % js_variable
507 app.add_js_file(None, body=js_text)
508 # We connect this function to the step after the builder is initialized
509 def setup(app):
510 # Tell Sphinx about this configuration variable
511 app.add_config_value('my_javascript_variable', 0, 'html')
512 # Run the function after the builder is initialized
513 app.connect('builder-inited', add_js_variable)
514
515 As a result, in your theme you can use code that depends on the presence of
516 this variable. Users can control the variable's value by defining it in their
517 :file:`conf.py` file.
518
519
520 .. [1] It is not an executable Python file, as opposed to :file:`conf.py`,
521 because that would pose an unnecessary security risk if themes are
522 shared.