Criando modelos¶
What Is Templating?¶
Modelagem ou templating é um método de geração de páginas HTML combinando modelos estáticos com dados variáveis. Os arquivos de template contêm as partes estáticas da saída HTML desejada e incluem uma sintaxe especial descrevendo como o conteúdo variável será inserido. Por exemplo, isso pode ser usado para inserir a data atual no rodapé de cada página ou para cercar o conteúdo principal do documento com um scaffold de HTML para fins de layout e formatação. Fazer isso requer apenas uma compreensão de HTML e da sintaxe de modelagem. Conhecimento de Python pode ser útil, mas não é obrigatório.
Templating uses an inheritance mechanism which allows child templates files (e.g. in a theme) to override as much (or as little) of their ‘parents’ as desired. Likewise, content authors can use their own local templates to override as much (or as little) of the theme templates as desired.
The result is that the Sphinx core, without needing to be changed, provides basic HTML generation, independent of the structure and appearance of the final output, while granting a great deal of flexibility to theme and content authors.
Sphinx Templating¶
Sphinx usa mecanismo de modelos do Jinja para HTML. Jinja é mecanismo baseado em texto, e inspirado nos modelos do Django, de forma que quem já usou Django tem familiaridade com Jinja. Também possui boa documentação para aqueles que precisam familiarizar-se com ele.
Preciso usar os modelos do Sphinx para produzir HTML?¶
Não. Você tem várias outras opções:
Você pode escrever uma subclasse
TemplateBridge
que chama o mecanismo de modelo de sua escolha e definir o valor de configuraçãotemplate_bridge
adequado.Você pode escrever um construtor personalizado que deriva de
StandaloneHTMLBuilder
e chama o mecanismo de modelo de sua escolha.Você pode usar o
PickleHTMLBuilder
que produz arquivos pickle com o conteúdo da página e pós-processá-los usando uma ferramenta personalizada ou usá-los em sua aplicação web.
Primer de criação de modelos em Jinja/Sphinx¶
A linguagem de modelagem padrão no Sphinx é Jinja. É inspirado no Django/Smarty e fácil de entender. O conceito mais importante no Jinja é herança de modelo, o que significa que você pode sobrescrever apenas blocos específicos dentro de um modelo, personalizando-o e ao mesmo tempo mantendo as alterações no mínimo.
Para personalizar a saída da sua documentação, você pode substituir todos os modelos (tanto os modelos de layout quanto os modelos filhos) adicionando arquivos com o mesmo nome do arquivo original no diretório de modelos da estrutura que a inicialização rápida (quickstart) do Sphinx gerou para você.
O Sphinx irá procurar por modelos nas pastas de templates_path
primeiro, e se não conseguir encontrar o modelo que está procurando lá, ele retornará aos modelos do tema selecionado.
Um modelo contém variáveis, que são substituídas por valores quando o modelo é avaliado, tags, que controlam a lógica do modelo e blocos que são usados para herança de modelo.
O tema basic do Sphinx fornece modelos básicos com alguns blocos que serão preenchidos com dados. Eles estão localizados no subdiretório themes/basic
do diretório de instalação do Sphinx e são usados por todos os temas integrados do Sphinx. Modelos com o mesmo nome em templates_path
substituem os modelos fornecidos pelo tema selecionado.
Por exemplo, para adicionar um novo link à área de modelos contendo links relacionados, tudo o que você precisa fazer é adicionar um novo modelo chamado layout.html
com o seguinte conteúdo:
{% extends "!layout.html" %}
{% block rootrellink %}
<li><a href="https://project.invalid/">Project Homepage</a> »</li>
{{ super() }}
{% endblock %}
Ao prefixar o nome do modelo substituído com um ponto de exclamação, o Sphinx carregará o modelo de layout do tema HTML subjacente.
Importante
Se você substituir um bloco, chame {{ super() }}
em algum lugar para renderizar o conteúdo original do bloco no modelo estendido – a menos que você não queira que esse conteúdo apareça.
Trabalhando com os modelos embutidos¶
O tema embutido basic fornece os modelos nos quais todos os temas embutidos do Sphinx são baseados. Possui os seguintes elementos que você pode substituir ou usar:
Blocos¶
Os seguintes blocos existem no modelo layout.html
:
doctype
O doctype do formato de saída. Por padrão, este é o XHTML 1.0 Transitional, pois é o mais próximo do que o Sphinx e o Docutils geram e é uma boa ideia não alterá-lo, a menos que você queira mudar para HTML 5 ou um tipo de documento XHTML diferente, mas compatível.
linktags
Este bloco adiciona algumas tags
<link>
à seção head do modelo.extrahead
Este bloco está vazio por padrão e pode ser usado para adicionar conteúdo extra na tag
<head>
do arquivo HTML gerado. Este é o lugar certo para adicionar referências a JavaScript ou arquivos CSS extras.relbar1
,relbar2
Este bloco contém a barra de relacionamento, a lista de links relacionados (os documentos pais à esquerda e os links para índice, módulos etc. à direita).
relbar1
aparece antes do documento,relbar2
depois do documento. Por padrão, ambos os blocos são preenchidos; para mostrar a relbar apenas antes do documento, você iria substituirrelbar2
assim:{% block relbar2 %}{% endblock %}
rootrellink
,relbaritems
Dentro do relbar existem três seções: O
rootrellink
, os links da documentação e osrelbaritems
personalizados. Orootrellink
é um bloco que por padrão contém um item de lista apontando para o documento raiz. Por padrão, orelbaritems
é um bloco vazio. Se você os substituir para adicionar links extras na barra, certifique-se de que sejam itens de lista e terminem comreldelim1
.document
O conteúdo do próprio documento. Ele contém o bloco “body” onde o conteúdo individual é colocado por submodelos como
page.html
.Nota
Para que a pesquisa embutida em JavaScript mostre uma visualização da página na página de resultados, o documento ou conteúdo do corpo deve ser envolvido em um elemento HTML contendo o atributo
role="main"
. Por exemplo:<div role="main"> {% block document %}{% endblock %} </div>
sidebar1
,sidebar2
Um possível local para uma barra lateral.
sidebar1
aparece antes do documento e está vazio por padrão,sidebar2
depois do documento e contém a barra lateral padrão. Se você quiser trocar o local da barra lateral, substitua isso e chame o helpersidebar
:{% block sidebar1 %}{{ sidebar() }}{% endblock %} {% block sidebar2 %}{% endblock %}
(A localização
sidebar2
para a barra lateral é necessária para a folha de estilosphinxdoc.css
, por exemplo.)sidebarlogo
The logo location within the sidebar. Override this if you want to place some content at the top of the sidebar.
footer
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
The table of contents within the sidebar.
Descontinuado desde a versão 1.0.
sidebarrel
The relation links (previous, next document) within the sidebar.
Descontinuado desde a versão 1.0.
sidebarsourcelink
The “Show source” link within the sidebar (normally only shown if this is enabled by
html_show_sourcelink
).Descontinuado desde a versão 1.0.
sidebarsearch
The search box within the sidebar. Override this if you want to place some content at the bottom of the sidebar.
Descontinuado desde a versão 1.0.
Variáveis de configuração¶
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
' »'
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.
Overriding works like this:
{% extends "!layout.html" %}
{% set reldelim1 = ' >' %}
- script_files¶
Add additional script files here, like this:
{% set script_files = script_files + ["_static/myscript.js"] %}
Descontinuado desde a versão 1.8.0: Please use
.Sphinx.add_js_file()
instead.
Helper Functions¶
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)¶
Check if a document with the name document exists.
- sidebar()¶
Return the rendered sidebar.
- relbar()¶
Return the rendered relation bar.
- warning(message)¶
Emit a warning message.
Global Variables¶
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
orhtmlhelp
).
- docstitle¶
The title of the documentation (the value of
html_title
), except when the “single-file” builder is used, when it is set toNone
.
- 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_url¶
The relative path to the HTML favicon image from the current document, or URL to the favicon, or
''
.Adicionado na versão 4.0.
- 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 reStructuredText document sources are copied (if
html_copy_source
isTrue
).
- last_updated¶
The build date.
- logo_url¶
The relative path to the HTML logo image from the current document, or URL to the logo, or
''
.Adicionado na versão 4.0.
- master_doc¶
- root_doc¶
The value of
master_doc
orroot_doc
(aliases), for usage withpathto()
.Adicionado na versão 4.0: The
root_doc
template variable.
- pagename¶
The “page name” of the current file, i.e. either the document name if the file is generated from a reStructuredText source, or the equivalent hierarchical name relative to the output directory (
[directory/]filename_without_extension
).
- rellinks¶
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¶
The value of
html_short_title
.
- show_source¶
True if
html_show_sourcelink
isTrue
.
- sphinx_version¶
The version of Sphinx used to build represented as a string for example “3.5.1”.
- sphinx_version_tuple¶
The version of Sphinx used to build represented as a tuple of five elements. For Sphinx version 3.5.1 beta 3 this would be
(3, 5, 1, 'beta', 3)
. The fourth element can be one of:alpha
,beta
,rc
,final
.final
always has 0 as the last element.Adicionado na versão 4.2.
- docutils_version_info¶
The version of Docutils used to build represented as a tuple of five elements. For Docutils version 0.16.1 beta 2 this would be
(0, 16, 1, 'beta', 2)
. The fourth element can be one of:alpha
,beta
,candidate
,final
.final
always has 0 as the last element.Adicionado na versão 5.0.2.
- styles¶
A list of the names of the main stylesheets as given by the theme or
html_style
.Adicionado na versão 5.1.
- title¶
The title of the current document, as used in the
<title>
tag.
- use_opensearch¶
The value of
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¶
A boolean that is True if the toc contains more than one entry.
- meta¶
Document metadata (a dictionary), see Metadados de todo o arquivo.
- next¶
The next document for the navigation. This variable is either false or has two attributes
link
andtitle
. 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.
- sourcename¶
The name of the copied source file for the current document. This is only nonempty if the
html_copy_source
value isTrue
. This has empty value on creating automatically-generated files.
- 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
If true, all TOC entries that are not ancestors of the current page are collapsed.
True
by default.maxdepth
The maximum depth of the tree. Set it to
-1
to allow unlimited depth. Defaults to the max depth selected in the toctree directive.titles_only
If true, put only top-level document titles in the tree.
False
by default.includehidden
If true, the ToC tree will also contain hidden entries.
False
by default.