如何从我的 .rst 文件访问 sphinx conf.py 中的变量?

How do I access a variable in sphinx conf.py from my .rst file?

我是 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!

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

如果你想让它随处可用,你可以这样做:

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 中的一堆变量,你可以使用以下解决方案(它基于 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

瞧瞧。

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