Debian Codegraph @

doc/development/html_themes/templating.rst

raw
1 .. highlight:: html+jinja
2
3 .. _templating:
4
5 ==========
6 Templating
7 ==========
8
9 What Is Templating?
10 -------------------
11
12 Templating is a method of generating HTML pages by combining static templates
13 with variable data.
14 The template files contain the static parts of the desired HTML output
15 and include special syntax describing how variable content will be inserted.
16 For example, this can be used to insert the current date in the footer of each page,
17 or to surround the main content of the document with a scaffold of HTML for layout
18 and formatting purposes.
19 Doing so only requires an understanding of HTML and the templating syntax.
20 Knowledge of Python can be helpful, but is not required.
21
22 Templating uses an inheritance mechanism which allows child templates files
23 (e.g. in a theme) to override as much (or as little) of their 'parents' as desired.
24 Likewise, content authors can use their own local templates to override as much (or
25 as little) of the theme templates as desired.
26
27 The result is that the Sphinx core, without needing to be changed, provides basic
28 HTML generation, independent of the structure and appearance of the final output,
29 while granting a great deal of flexibility to theme and content authors.
30
31
32 Sphinx Templating
33 -----------------
34
35 Sphinx uses the `Jinja <https://jinja.palletsprojects.com/>`_ templating engine
36 for its HTML templates. Jinja is a text-based engine, inspired by Django
37 templates, so anyone having used Django will already be familiar with it. It
38 also has excellent documentation for those who need to make themselves familiar
39 with it.
40
41
42 Do I need to use Sphinx's templates to produce HTML?
43 ----------------------------------------------------
44
45 No. You have several other options:
46
47 * You can write a :class:`~sphinx.application.TemplateBridge` subclass that
48 calls your template engine of choice, and set the :confval:`template_bridge`
49 configuration value accordingly.
50
51 * You can :ref:`write a custom builder <writing-builders>` that derives from
52 :class:`~sphinx.builders.html.StandaloneHTMLBuilder` and calls your template
53 engine of choice.
54
55 * You can use the :class:`~sphinxcontrib.serializinghtml.PickleHTMLBuilder` that
56 produces pickle files with the page contents, and postprocess them using a
57 custom tool, or use them in your Web application.
58
59 .. _templating-primer:
60
61 Jinja/Sphinx Templating Primer
62 ------------------------------
63
64 The default templating language in Sphinx is Jinja. It's Django/Smarty inspired
65 and easy to understand. The most important concept in Jinja is :dfn:`template
66 inheritance`, which means that you can overwrite only specific blocks within a
67 template, customizing it while also keeping the changes at a minimum.
68
69 To customize the output of your documentation you can override all the templates
70 (both the layout templates and the child templates) by adding files with the
71 same name as the original filename into the template directory of the structure
72 the Sphinx quickstart generated for you.
73
74 Sphinx will look for templates in the folders of :confval:`templates_path`
75 first, and if it can't find the template it's looking for there, it falls back
76 to the selected theme's templates.
77
78 A template contains **variables**, which are replaced with values when the
79 template is evaluated, **tags**, which control the logic of the template and
80 **blocks** which are used for template inheritance.
81
82 Sphinx's *basic* theme provides base templates with a couple of blocks it will
83 fill with data. These are located in the :file:`themes/basic` subdirectory of
84 the Sphinx installation directory, and used by all builtin Sphinx themes.
85 Templates with the same name in the :confval:`templates_path` override templates
86 supplied by the selected theme.
87
88 For example, to add a new link to the template area containing related links all
89 you have to do is to add a new template called ``layout.html`` with the
90 following contents::
91
92 {% extends "!layout.html" %}
93 {% block rootrellink %}
94 <li><a href="https://project.invalid/">Project Homepage</a> &raquo;</li>
95 {{ super() }}
96 {% endblock %}
97
98 By prefixing the name of the overridden template with an exclamation mark,
99 Sphinx will load the layout template from the underlying HTML theme.
100
101 .. important::
102 If you override a block, call ``{{ super() }}`` somewhere to render the
103 block's original content in the extended template -- unless you don't want
104 that content to show up.
105
106
107 Working with the builtin templates
108 ----------------------------------
109
110 The builtin **basic** theme supplies the templates that all builtin Sphinx
111 themes are based on. It has the following elements you can override or use:
112
113 Blocks
114 ~~~~~~
115
116 The following blocks exist in the ``layout.html`` template:
117
118 ``doctype``
119 The doctype of the output format. By default this is XHTML 1.0 Transitional
120 as this is the closest to what Sphinx and Docutils generate and it's a good
121 idea not to change it unless you want to switch to HTML 5 or a different but
122 compatible XHTML doctype.
123
124 ``linktags``
125 This block adds a couple of ``<link>`` tags to the head section of the
126 template.
127
128 ``extrahead``
129 This block is empty by default and can be used to add extra contents into
130 the ``<head>`` tag of the generated HTML file. This is the right place to
131 add references to JavaScript or extra CSS files.
132
133 ``relbar1``, ``relbar2``
134 This block contains the *relation bar*, the list of related links (the
135 parent documents on the left, and the links to index, modules etc. on the
136 right). ``relbar1`` appears before the document, ``relbar2`` after the
137 document. By default, both blocks are filled; to show the relbar only
138 before the document, you would override ``relbar2`` like this::
139
140 {% block relbar2 %}{% endblock %}
141
142 ``rootrellink``, ``relbaritems``
143 Inside the relbar there are three sections: The ``rootrellink``, the links
144 from the documentation and the custom ``relbaritems``. The ``rootrellink``
145 is a block that by default contains a list item pointing to the root
146 document by default, the ``relbaritems`` is an empty block. If you
147 override them to add extra links into the bar make sure that they are list
148 items and end with the :data:`reldelim1`.
149
150 ``document``
151 The contents of the document itself. It contains the block "body" where
152 the individual content is put by subtemplates like ``page.html``.
153
154 .. note::
155 In order for the built-in JavaScript search to show a page preview on
156 the results page, the document or body content should be wrapped in an
157 HTML element containing the ``role="main"`` attribute. For example::
158
159 <div role="main">
160 {% block document %}{% endblock %}
161 </div>
162
163 ``sidebar1``, ``sidebar2``
164 A possible location for a sidebar. ``sidebar1`` appears before the document
165 and is empty by default, ``sidebar2`` after the document and contains the
166 default sidebar. If you want to swap the sidebar location override this and
167 call the ``sidebar`` helper::
168
169 {% block sidebar1 %}{{ sidebar() }}{% endblock %}
170 {% block sidebar2 %}{% endblock %}
171
172 (The ``sidebar2`` location for the sidebar is needed by the ``sphinxdoc.css``
173 stylesheet, for example.)
174
175 ``sidebarlogo``
176 The logo location within the sidebar. Override this if you want to place
177 some content at the top of the sidebar.
178
179 ``footer``
180 The block for the footer div. If you want a custom footer or markup before
181 or after it, override this one.
182
183 The following four blocks are *only* used for pages that do not have assigned a
184 list of custom sidebars in the :confval:`html_sidebars` config value. Their use
185 is deprecated in favor of separate sidebar templates, which can be included via
186 :confval:`html_sidebars`.
187
188 ``sidebartoc``
189 The table of contents within the sidebar.
190
191 .. deprecated:: 1.0
192
193 ``sidebarrel``
194 The relation links (previous, next document) within the sidebar.
195
196 .. deprecated:: 1.0
197
198 ``sidebarsourcelink``
199 The "Show source" link within the sidebar (normally only shown if this is
200 enabled by :confval:`html_show_sourcelink`).
201
202 .. deprecated:: 1.0
203
204 ``sidebarsearch``
205 The search box within the sidebar. Override this if you want to place some
206 content at the bottom of the sidebar.
207
208 .. deprecated:: 1.0
209
210
211 Configuration Variables
212 ~~~~~~~~~~~~~~~~~~~~~~~
213
214 Inside templates you can set a couple of variables used by the layout template
215 using the ``{% set %}`` tag:
216
217 .. data:: reldelim1
218
219 The delimiter for the items on the left side of the related bar. This
220 defaults to ``' &raquo;'`` Each item in the related bar ends with the value
221 of this variable.
222
223 .. data:: reldelim2
224
225 The delimiter for the items on the right side of the related bar. This
226 defaults to ``' |'``. Each item except of the last one in the related bar
227 ends with the value of this variable.
228
229 Overriding works like this::
230
231 {% extends "!layout.html" %}
232 {% set reldelim1 = ' &gt;' %}
233
234 .. data:: script_files
235
236 Add additional script files here, like this::
237
238 {% set script_files = script_files + ["_static/myscript.js"] %}
239
240 .. deprecated:: 1.8.0
241
242 Please use ``.Sphinx.add_js_file()`` instead.
243
244 Helper Functions
245 ~~~~~~~~~~~~~~~~
246
247 Sphinx provides various Jinja functions as helpers in the template. You can use
248 them to generate links or output multiply used elements.
249
250 .. function:: pathto(document)
251
252 Return the path to a Sphinx document as a URL. Use this to refer to built
253 documents.
254
255 .. function:: pathto(file, 1)
256 :no-index:
257
258 Return the path to a *file* which is a filename relative to the root of the
259 generated output. Use this to refer to static files.
260
261 .. function:: hasdoc(document)
262
263 Check if a document with the name *document* exists.
264
265 .. function:: sidebar()
266
267 Return the rendered sidebar.
268
269 .. function:: relbar()
270
271 Return the rendered relation bar.
272
273 .. function:: warning(message)
274
275 Emit a warning message.
276
277 Global Variables
278 ~~~~~~~~~~~~~~~~
279
280 These global variables are available in every template and are safe to use.
281 There are more, but most of them are an implementation detail and might change
282 in the future.
283
284 .. data:: builder
285
286 The name of the builder (e.g. ``html`` or ``htmlhelp``).
287
288 .. data:: copyright
289
290 The value of :confval:`copyright`.
291
292 .. data:: docstitle
293
294 The title of the documentation (the value of :confval:`html_title`), except
295 when the "single-file" builder is used, when it is set to ``None``.
296
297 .. data:: embedded
298
299 True if the built HTML is meant to be embedded in some viewing application
300 that handles navigation, not the web browser, such as for HTML help or Qt
301 help formats. In this case, the sidebar is not included.
302
303 .. data:: favicon_url
304
305 The relative path to the HTML favicon image from the current document, or
306 URL to the favicon, or ``''``.
307
308 .. versionadded:: 4.0
309
310 .. data:: file_suffix
311
312 The value of the builder's :attr:`~.SerializingHTMLBuilder.out_suffix`
313 attribute, i.e. the file name extension that the output files will get. For
314 a standard HTML builder, this is usually ``.html``.
315
316 .. data:: has_source
317
318 True if the reStructuredText document sources are copied
319 (if :confval:`html_copy_source` is ``True``).
320
321 .. data:: language
322
323 The value of :confval:`language`.
324
325 .. data:: last_updated
326
327 The build date.
328
329 .. data:: logo_url
330
331 The relative path to the HTML logo image from the current document, or URL
332 to the logo, or ``''``.
333
334 .. versionadded:: 4.0
335
336 .. data:: master_doc
337 root_doc
338
339 The value of :confval:`master_doc` or :confval:`root_doc` (aliases),
340 for usage with :func:`pathto`.
341
342 .. versionadded:: 4.0
343 The :data:`!root_doc` template variable.
344
345 .. data:: pagename
346
347 The "page name" of the current file, i.e. either the document name if the
348 file is generated from a reStructuredText source,
349 or the equivalent hierarchical name relative to the output directory
350 (``[directory/]filename_without_extension``).
351
352 .. data:: project
353
354 The value of :confval:`project`.
355
356 .. data:: release
357
358 The value of :confval:`release`.
359
360 .. data:: rellinks
361
362 A list of links to put at the left side of the relbar, next to "next" and
363 "prev". This usually contains links to the general index and other indices,
364 such as the Python module index. If you add something yourself, it must be a
365 tuple ``(pagename, link title, accesskey, link text)``.
366
367 .. data:: shorttitle
368
369 The value of :confval:`html_short_title`.
370
371 .. data:: show_source
372
373 True if :confval:`html_show_sourcelink` is ``True``.
374
375 .. data:: sphinx_version
376
377 The version of Sphinx used to build represented as a string for example "3.5.1".
378
379 .. data:: sphinx_version_tuple
380
381 The version of Sphinx used to build represented as a tuple of five elements.
382 For Sphinx version 3.5.1 beta 3 this would be ``(3, 5, 1, 'beta', 3)``.
383 The fourth element can be one of: ``alpha``, ``beta``, ``rc``, ``final``.
384 ``final`` always has 0 as the last element.
385
386 .. versionadded:: 4.2
387
388 .. data:: docutils_version_info
389
390 The version of Docutils used to build represented as a tuple of five elements.
391 For Docutils version 0.16.1 beta 2 this would be ``(0, 16, 1, 'beta', 2)``.
392 The fourth element can be one of: ``alpha``, ``beta``, ``candidate``, ``final``.
393 ``final`` always has 0 as the last element.
394
395 .. versionadded:: 5.0.2
396
397 .. data:: styles
398
399 A list of the names of the main stylesheets as given by the theme or
400 :confval:`html_style`.
401
402 .. versionadded:: 5.1
403
404 .. data:: title
405
406 The title of the current document, as used in the ``<title>`` tag.
407
408 .. data:: use_opensearch
409
410 The value of :confval:`html_use_opensearch`.
411
412 .. data:: version
413
414 The value of :confval:`version`.
415
416
417 In addition to these values, there are also all **theme options** available
418 (prefixed by ``theme_``), as well as the values given by the user in
419 :confval:`html_context`.
420
421 In documents that are created from source files (as opposed to
422 automatically-generated files like the module index, or documents that already
423 are in HTML form), these variables are also available:
424
425 .. data:: body
426
427 A string containing the content of the page in HTML form as produced by the
428 HTML builder, before the theme is applied.
429
430 .. data:: display_toc
431
432 A boolean that is True if the toc contains more than one entry.
433
434 .. data:: meta
435
436 Document metadata (a dictionary), see :ref:`metadata`.
437
438 .. data:: metatags
439
440 A string containing the page's HTML :dudir:`meta` tags.
441
442 .. data:: next
443
444 The next document for the navigation. This variable is either false or has
445 two attributes ``link`` and ``title``. The title contains HTML markup. For
446 example, to generate a link to the next page, you can use this snippet::
447
448 {% if next %}
449 <a href="{{ next.link|e }}">{{ next.title }}</a>
450 {% endif %}
451
452 .. data:: page_source_suffix
453
454 The suffix of the file that was rendered. Since we support a list of
455 :confval:`source_suffix`, this will allow you to properly link to the
456 original source file.
457
458 .. data:: parents
459
460 A list of parent documents for navigation, structured like the :data:`next`
461 item.
462
463 .. data:: prev
464
465 Like :data:`next`, but for the previous page.
466
467 .. data:: sourcename
468
469 The name of the copied source file for the current document. This is only
470 nonempty if the :confval:`html_copy_source` value is ``True``.
471 This has empty value on creating automatically-generated files.
472
473 .. data:: toc
474
475 The local table of contents for the current page, rendered as HTML bullet
476 lists.
477
478 .. data:: toctree
479
480 A callable yielding the global TOC tree containing the current page, rendered
481 as HTML bullet lists. Optional keyword arguments:
482
483 ``collapse``
484 If true, all TOC entries that are not ancestors of the current page are
485 collapsed.
486 ``True`` by default.
487
488 ``maxdepth``
489 The maximum depth of the tree. Set it to ``-1`` to allow unlimited depth.
490 Defaults to the max depth selected in the toctree directive.
491
492 ``titles_only``
493 If true, put only top-level document titles in the tree.
494 ``False`` by default.
495
496 ``includehidden``
497 If true, the ToC tree will also contain hidden entries.
498 ``False`` by default.