变量替换在 Sphinx 中无法正常工作

Variable substitution not working properly in Sphinx

我有一个用 Sphinx 制作的文档项目。我通过配置键 rst_epilog 使用全局变量。我的 conf.py 文件包含以下内容:

rst_epilog = """
.. |MY_VERSION| replace:: 2.1.0
"""

然后,在第一个页面中,我使用以前定义的变量 (VERSION),如下所示:

The version of my repo is: |MY_VERSION|

.. sourcecode:: bash

    git clone https://github.com/my-organization/my-repo.git
    cd my-repo
    git checkout |MY_VERSION|

构建文档后,在生成的 HTML 中,第一个变量被正确替换,但第二个变量未被正确替换:

很明显,替换在格式化的源代码块中不起作用,这非常不方便。

是否可以解决此问题?

PS:我也尝试了 rst_prolog,结果相同。

这将使替换生效:

.. parsed-literal::

   git clone https://github.com/my-organization/my-repo.git
   cd my-repo
   git checkout |MY_VERSION|

使用 parsed-literal 指令,您可以进行替换(和其他内联标记),但没有语法高亮显示。

使用code-block(或sourcecode,或highlight),您可以进行语法高亮,但不处理内联标记。

我创建了一个 Sphinx 扩展,它为此提供了 substitution-code-block

它允许您在 conf.py 中定义 substitutions,然后在 .. substitution-code-block 块中使用这些替换。

此分机位于 https://github.com/adamtheturtle/sphinx-substitution-extensions

但是,这是非常少量的代码。 要在没有第三方扩展的情况下在您自己的代码库中启用此功能,请在您的代码库中创建一个包含以下内容的模块:

"""
Custom Sphinx extensions.
"""

from typing import List

from sphinx.application import Sphinx
from sphinx.directives.code import CodeBlock


class SubstitutionCodeBlock(CodeBlock):  # type: ignore
    """
    Similar to CodeBlock but replaces placeholders with variables.
    """

    def run(self) -> List:
        """
        Replace placeholders with given variables.
        """
        app = self.state.document.settings.env.app
        new_content = []
        self.content = self.content  # type: List[str]
        existing_content = self.content
        for item in existing_content:
            for pair in app.config.substitutions:
                original, replacement = pair
                item = item.replace(original, replacement)
            new_content.append(item)

        self.content = new_content
        return list(CodeBlock.run(self))


def setup(app: Sphinx) -> None:
    """
    Add the custom directives to Sphinx.
    """
    app.add_config_value('substitutions', [], 'html')
    app.add_directive('substitution-code-block', SubstitutionCodeBlock)

然后,使用 conf.py 中定义的 extensions 模块。 然后,在 conf.py 中设置 substitutions 变量,例如[('|foo|', 'bar')] 在每个 substitution-code-block.

中用 bar 替换 |foo|