14

I'm brand new to Sphinx and reStructuredText.

Inside my Sphinx conf.py I defined:

version = '0.0.2'

Inside of tutorial.rst I want access the version variable and display 0.0.2 in my html file. I tried:

version

|version|

:version:

.. |version|

.. :version:

I succeeded in testing the contents of the version.

.. ifconfig:: version == '0.0.2'

    This prints!

This was encouraging, but not what I want.

barryhunter
  • 20,886
  • 3
  • 30
  • 43
nu everest
  • 9,589
  • 12
  • 71
  • 90

2 Answers2

13

If you want this to be available everywhere, you can do something like this:

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!

The rst_epilog list makes items within it globally-available to compiled .rst files. See http://www.sphinx-doc.org/en/master/usage/configuration.html#confval-rst_epilog

Eric Clack
  • 1,886
  • 1
  • 15
  • 28
Chris
  • 158
  • 3
  • 10
3

Late to the party. If you have a bunch of variables inside conf.py that you want to use in your rst files you can use the following solution (it is based on Chris answer). Let suppose in the conf.py there are declarations like:

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

open conf.py and append at the end of the file the following:

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

Now perform:

make html

and voilà.

BTW "project, copyright, versions" are just some test variables.

Koldar
  • 1,317
  • 15
  • 35