我尝试在 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 上述错误转换为警告)。
最佳答案
如果不更改 code-block
,这是不可能的。
为此,我创建了一个 Sphinx 扩展,它提供了 substitution-code-block
。
它允许您在 conf.py
中定义 substitutions
,然后在 ..substitution-code-block
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 中的
。|foo|
替换为 bar
- block
关于python-sphinx - 如何在代码块中使用替换定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44761197/