【问题标题】:How do I access a variable in sphinx conf.py from my .rst file?如何从我的 .rst 文件访问 sphinx conf.py 中的变量?
【发布时间】:2015-11-30 19:51:28
【问题描述】:

我是 Sphinx 和 reStructuredText 的新手。

在我的 Sphinx conf.py 中我定义了:

version = '0.0.2'

tutorial.rst 内部,我想访问version 变量并在我的html 文件中显示0.0.2。我试过了:

version

|version|

:version:

.. |version|

.. :version:

版本内容测试成功。

.. ifconfig:: version == '0.0.2'

    This prints!

这令人鼓舞,但不是我想要的。

【问题讨论】:

    标签: python python-sphinx restructuredtext


    【解决方案1】:

    如果你想让它在任何地方都可用,你可以这样做:

    conf.py

    rst_epilog = """
    .. |ProjectVersion| replace:: Foo Project, version {versionnum}
    """.format(
    versionnum = version,
    )
    

    file.rst

    As one may see, we have made significant strides in |ProjectVersion| 
    and hope that you enjoy the product!
    

    rst_epilog 列表使其中的项目对已编译的 .rst 文件全局可用。见http://www.sphinx-doc.org/en/master/usage/configuration.html#confval-rst_epilog

    【讨论】:

    • 由于在读取 conf.py 文件时会评估 rst_epilog,因此不会以这种方式考虑使用 -D 覆盖的配置值。
    • .. code-block 指令中使用|ProjectVersion| 似乎不起作用。
    【解决方案2】:

    聚会迟到了。如果您想在您的 rst 文件中使用 conf.py 中的一堆变量,您可以使用以下解决方案(它基于 Chris 的回答)。 假设在conf.py 中有如下声明:

    version = "1.0.0"
    copyright = "Mario, 2010"
    project = "foobar"
    

    打开 conf.py 并在文件末尾附加以下内容:

    variables_to_export = [
        "project",
        "copyright",
        "version",
    ]
    frozen_locals = dict(locals())
    rst_epilog = '\n'.join(map(lambda x: f".. |{x}| replace:: {frozen_locals[x]}", variables_to_export))
    del frozen_locals
    

    现在执行:

    make html
    

    然后瞧。

    顺便说一句,“项目、版权、版本”只是一些测试变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      相关资源
      最近更新 更多