【问题标题】:Variable substitution not working properly in Sphinx变量替换在 Sphinx 中无法正常工作
【发布时间】:2017-06-28 17:26:14
【问题描述】:

我有一个使用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,结果相同。

【问题讨论】:

    标签: python versioning python-sphinx substitution restructuredtext


    【解决方案1】:

    这将使替换工作:

    .. 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),您可以进行语法高亮,但不处理内联标记。

    【讨论】:

      【解决方案2】:

      为此,我创建了一个 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-28
        • 1970-01-01
        • 2021-04-17
        • 1970-01-01
        相关资源
        最近更新 更多