模板

Sphinx uses the Jinja templating engine for its HTML templates. Jinja is a text-based engine, and inspired by Django templates, so anyone having used Django will already be familiar with it. It also has excellent documentation for those who need to make themselves familiar with it.

我是否需要使用Sphinx的模板来生成HTML?

不,您还有其他几种选择:

  • You can write a TemplateBridge subclass that calls your template engine of choice, and set the template_bridge configuration value accordingly.
  • You can write a custom builder that derives from StandaloneHTMLBuilder and calls your template engine of choice.
  • You can use the PickleHTMLBuilder that produces pickle files with the page contents, and postprocess them using a custom tool, or use them in your Web application.

Jinja/Sphinx 模板入门

The default templating language in Sphinx is Jinja. It’s Django/Smarty inspired and easy to understand. The most important concept in Jinja is template inheritance, which means that you can overwrite only specific blocks within a template, customizing it while also keeping the changes at a minimum.

To customize the output of your documentation you can override all the templates (both the layout templates and the child templates) by adding files with the same name as the original filename into the template directory of the structure the Sphinx quickstart generated for you.

Sphinx will look for templates in the folders of templates_path first, and if it can’t find the template it’s looking for there, it falls back to the selected theme’s templates.

A template contains variables, which are replaced with values when the template is evaluated, tags, which control the logic of the template and blocks which are used for template inheritance.

Sphinx’s basic theme provides base templates with a couple of blocks it will fill with data. These are located in the themes/basic subdirectory of the Sphinx installation directory, and used by all builtin Sphinx themes. Templates with the same name in the templates_path override templates supplied by the selected theme.

For example, to add a new link to the template area containing related links all you have to do is to add a new template called layout.html with the following contents:

{% extends "!layout.html" %}
{% block rootrellink %}
    <li><a href="https://project.invalid/">Project Homepage</a> &raquo;</li>
    {{ super() }}
{% endblock %}

By prefixing the name of the overridden template with an exclamation mark, Sphinx will load the layout template from the underlying HTML theme.

Important: If you override a block, call {{ super() }} somewhere to render the block’s original content in the extended template – unless you don’t want that content to show up.

使用内置模板

The builtin basic theme supplies the templates that all builtin Sphinx themes are based on. It has the following elements you can override or use:

Blocks

layout.html 模板中存在以下块:

doctype
输出格式的doctype。默认情况下,这是XHTML 1.0 Transitional,因为它最接近Sphinx和Docutils生成的内容,除非您想要切换到HTML 5或不同但兼容的XHTML doctype,否则最好不要更改它。
linktags
这个块在模板的head部分添加了几个 <link> 标签。
extrahead
This block is empty by default and can be used to add extra contents into the <head> tag of the generated HTML file. This is the right place to add references to JavaScript or extra CSS files.
relbar1 / relbar2

This block contains the relation bar, the list of related links (the parent documents on the left, and the links to index, modules etc. on the right). relbar1 appears before the document, relbar2 after the document. By default, both blocks are filled; to show the relbar only before the document, you would override relbar2 like this:

{% block relbar2 %}{% endblock %}
rootrellink / relbaritems
Inside the relbar there are three sections: The rootrellink, the links from the documentation and the custom relbaritems. The rootrellink is a block that by default contains a list item pointing to the master document by default, the relbaritems is an empty block. If you override them to add extra links into the bar make sure that they are list items and end with the reldelim1.
文档
The contents of the document itself. It contains the block “body” where the individual content is put by subtemplates like page.html.
sidebar1 / sidebar2

A possible location for a sidebar. sidebar1 appears before the document and is empty by default, sidebar2 after the document and contains the default sidebar. If you want to swap the sidebar location override this and call the sidebar helper:

{% block sidebar1 %}{{ sidebar() }}{% endblock %}
{% block sidebar2 %}{% endblock %}

(The sidebar2 location for the sidebar is needed by the sphinxdoc.css stylesheet, for example.)

sidebarlogo
The logo location within the sidebar. Override this if you want to place some content at the top of the sidebar.
页脚
The block for the footer div. If you want a custom footer or markup before or after it, override this one.

The following four blocks are only used for pages that do not have assigned a list of custom sidebars in the html_sidebars config value. Their use is deprecated in favor of separate sidebar templates, which can be included via html_sidebars.

sidebartoc

侧栏内的目录。

1.0 版后已移除.

sidebarrel

边栏内的关系链接(上一个,下一个文档)。

1.0 版后已移除.

sidebarsourcelink

The “Show source” link within the sidebar (normally only shown if this is enabled by html_show_sourcelink).

1.0 版后已移除.

sidebarsearch

The search box within the sidebar. Override this if you want to place some content at the bottom of the sidebar.

1.0 版后已移除.

配置变量

Inside templates you can set a couple of variables used by the layout template using the {% set %} tag:

reldelim1

The delimiter for the items on the left side of the related bar. This defaults to ' &raquo;' Each item in the related bar ends with the value of this variable.

reldelim2

The delimiter for the items on the right side of the related bar. This defaults to ' |'. Each item except of the last one in the related bar ends with the value of this variable.

覆盖就是这样的:

{% extends "!layout.html" %}
{% set reldelim1 = ' &gt;' %}
script_files

在这里添加其他脚本文件,如下所示:

{% set script_files = script_files + ["_static/myscript.js"] %}

1.8.0 版后已移除: 请用 .Sphinx.add_js_file() 代替.

助手功能

Sphinx provides various Jinja functions as helpers in the template. You can use them to generate links or output multiply used elements.

pathto(document)

Return the path to a Sphinx document as a URL. Use this to refer to built documents.

pathto(file, 1)

Return the path to a file which is a filename relative to the root of the generated output. Use this to refer to static files.

hasdoc(document)

检查是否存在名为 document 的文档。

返回渲染的侧边栏。

relbar()

返回渲染的关系栏。

warning(message)

发出警告信息。

全局变量

These global variables are available in every template and are safe to use. There are more, but most of them are an implementation detail and might change in the future.

builder

The name of the builder (e.g. html or htmlhelp).

价值 copyright

docstitle

The title of the documentation (the value of html_title), except when the “single-file” builder is used, when it is set to None.

embedded

True if the built HTML is meant to be embedded in some viewing application that handles navigation, not the web browser, such as for HTML help or Qt help formats. In this case, the sidebar is not included.

favicon

静态路径中 HTML favicon 的路径,或者 ''

file_suffix

The value of the builder’s out_suffix attribute, i.e. the file name extension that the output files will get. For a standard HTML builder, this is usually .html.

has_source

True if the reST document sources are copied (if html_copy_source is True).

language

language 的值 。

last_updated

构建日期。

The path to the HTML logo image in the static path, or ''.

master_doc

master_doc 的值, 用于 pathto().

pagename

The “page name” of the current file, i.e. either the document name if the file is generated from a reST source, or the equivalent hierarchical name relative to the output directory ([directory/]filename_without_extension).

project

project

release

release

A list of links to put at the left side of the relbar, next to “next” and “prev”. This usually contains links to the general index and other indices, such as the Python module index. If you add something yourself, it must be a tuple (pagename, link title, accesskey, link text).

shorttitle

html_short_title

show_source

True if html_show_sourcelink is True.

sphinx_version

用于构建的Sphinx版本。

style

The name of the main stylesheet, as given by the theme or html_style.

title

当前文档的标题,在 <title> 标签中使用。

use_opensearch

html_use_opensearch

version

html_use_opensearch

In addition to these values, there are also all theme options available (prefixed by theme_), as well as the values given by the user in html_context.

In documents that are created from source files (as opposed to automatically-generated files like the module index, or documents that already are in HTML form), these variables are also available:

body

A string containing the content of the page in HTML form as produced by the HTML builder, before the theme is applied.

display_toc

如果toc包含多个条目,则为布尔值为True。

meta

文档元数据(字典),请参阅 File-wide metadata

metatags

包含页面HTML meta 标签的字符串。

next

The next document for the navigation. This variable is either false or has two attributes link and title. The title contains HTML markup. For example, to generate a link to the next page, you can use this snippet:

{% if next %}
<a href="{{ next.link|e }}">{{ next.title }}</a>
{% endif %}
page_source_suffix

The suffix of the file that was rendered. Since we support a list of source_suffix, this will allow you to properly link to the original source file.

parents

A list of parent documents for navigation, structured like the next item.

prev

喜欢 next,但是对于上一页。

sourcename

The name of the copied source file for the current document. This is only nonempty if the html_copy_source value is True. This has empty value on creating automatically-generated files.

title

页面标题。

toc

The local table of contents for the current page, rendered as HTML bullet lists.

toctree

A callable yielding the global TOC tree containing the current page, rendered as HTML bullet lists. Optional keyword arguments:

  • collapse (True by default): if true, all TOC entries that are not ancestors of the current page are collapsed
  • maxdepth (defaults to the max depth selected in the toctree directive): the maximum depth of the tree; set it to -1 to allow unlimited depth
  • titles_only (False by default): if true, put only toplevel document titles in the tree
  • includehidden (False by default): if true, the TOC tree will also contain hidden entries.