首页 > 解决方案 > 可以使用 `ifconfig` 块 (reStructuredText) 有条件地定义目标

问题描述

是否可以使用ifconfig有条件地在 reStructuredText 文件中定义目标

我在我的 sphinxconf.py文件中设置了一个变量,我想用它来有条件地确定文档中目标的 URI:

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')

我的index.rst文件有以下内容:

test link to target1_

.. ifconfig:: buildername == 'html'

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

上述工作按预期工作,“target1”成为一个超链接example.com/a

但是,如果我想target1根据配置变量的值实际定义为有条件地设置为两个选项之一buildername,那么我有

test link to target1_

.. ifconfig:: buildername == 'html'

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

.. ifconfig:: buildername != 'html'

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

不仅上述输出不适用于example.com/b,而且它破坏了第一个链接,target1现在指向任何内容(实际上#id3)。

此外,我在sphinx-build输出中收到以下警告

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".
...

是否可以在一个.rst文件中定义相同的目标两次,这样每个定义都包含在一个ifconfig指令中?

标签: python-sphinxrestructuredtext

解决方案


不幸的是,我不认为你想要什么是可能的。您可以抑制警告(这可能不是一个好主意),或者您可以添加更多标记以通过目标和链接之间的一对一关系来避免它们。

.. 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

推荐阅读