Possible to define a target conditonally using `ifconfig` block (reStructuredText)

Viewed 183

Is it possible to condtionally define a target in a reStructuredText file using ifconfig?

I've set a variable in my sphinx conf.py file that I want to use to conditionally determine the URI of a target in my documentation:

def setup(app):

    argv = ' '.join(sys.argv)
    if '-b html' in argv:
        app.add_config_value('buildername', 'html', 'env')
    else:
        app.add_config_value('buildername', 'not-html', 'env')

And my index.rst file has the following content:

test link to target1_

.. ifconfig:: buildername == 'html'

  .. _target1: https://example.com/a

The above works as expected, and "target1" becomes a hyperlink to example.com/a

But if I want to actually define target1 to be conditionally set to one of two options based on the value of the buildername config var, then I have

test link to target1_

.. ifconfig:: buildername == 'html'

  .. _target1: https://example.com/a

.. ifconfig:: buildername != 'html'

  .. _target1: https://example.com/b

Not only does the above output not work for example.com/b, but it breaks the first link and target1 now points to nothing (actually #id3).

Moreover, I get the following warnings in my sphinx-build output

user@host:~$ make clean && sphinx-build -b html . _build/html/
...
reading sources... [100%] support                                               
.../index.rst:16: WARNING: Duplicate explicit target name: "target1".
.../index.rst:8: WARNING: Duplicate target name, cannot be used as a unique reference: "target1".
...

Is it possible to define the same target twice within a .rst file, such that each definition is wrapped in an ifconfig directive?

1 Answers

Unfortunately, I do not think what you want is possible. You could suppress warnings (which is probably not a good idea), or you could add more markup to avoid them through a one-to-one relationship between target and link.

.. ifconfig:: buildername == 'html'

    test link to target1_

.. ifconfig:: buildername == 'html'

    .. _target1: https://example.com/a

.. ifconfig:: buildername != 'html'

    test link to target2_

.. ifconfig:: buildername != 'html'

    .. _target2: https://example.com/b
Related