【问题标题】:How to use substitution definitions with code blocks?如何将替换定义与代码块一起使用?
【发布时间】:2017-06-26 13:43:21
【问题描述】:

我尝试在 Sphinx 文档中将替换定义与代码块一起使用,但它不起作用。这是我的 ReST 源代码:

.. |foo| code-block:: python

   foo = 1

|foo|

Sphinx 抛出以下错误:

/.../examples.rst:184: WARNING: Substitution definition "foo" empty or invalid.

.. |foo| code-block:: python

   foo = 1

/.../examples.rst:193: ERROR: Undefined substitution referenced: "foo".

我怎样才能使这个例子工作?


  • Sphinx 版本: 1.5.5(使用 Sphinx 1.6.2 上述错误会转化为警告)。

【问题讨论】:

标签: python-sphinx substitution restructuredtext


【解决方案1】:

如果不更改 code-block,这是不可能的。 为此,我创建了一个 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 中的|foo| 替换为bar

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2013-02-06
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多