Sphinx: Use a different directive for a different

2020-04-28 05:57发布

Assume you have a reStructuredText document and want to export it in two formats using Sphinx 2.x: HTML and PDF.

You want to put some slightly different contents in these two formats. For example, the text "I am HTML" appears in the HTML version whereas "I am PDF" appears in the PDF version in the same location of the document.

Use a replace directive like below will give you "I am HTML" regardless of the export format.

.. |foo| replace:: HTML

⋮

I am |foo|

Can you use a different directive for a different export format?

2条回答
smile是对你的礼貌
2楼-- · 2020-04-28 06:25

A solution could be to define a rst_prolog (or rst_epilog) dynamically based on some tag (could be the builder tag for example).

conf.py:

prolog_for_html = """
.. |document_type| replace:: HTML
"""

prolog_for_latex = """
.. |document_type| replace:: latex
"""

if tags.has('html_prolog'):
    rst_prolog = prolog_for_html
elif tags.has('latex_prolog'):
    rst_prolog = prolog_for_latex

document.rst

This is a |document_type| document.

Makefile

html latex:
    sphinx-build -t $@_prolog -b $@ src build/$@
查看更多
放荡不羁爱自由
3楼-- · 2020-04-28 06:34

This is a little clunky, but it works for me:

.. role:: latex(raw)
   :format: latex

.. role:: html(raw)
   :format: html

.. |foo| replace:: :latex:`LaTeX text`:html:`HTML text`
.. |bar| replace:: :latex:`other latex text`:html:`other html text`
查看更多
登录 后发表回答