Search code examples
python-sphinxrestructuredtextcross-reference

How to link duplicate targets in reStructuredText?


I have two duplicate keys -> .. command:: targetName in my doc on two separate pages. I need to know how can I link to these two separate targets using the following syntax:

Page-1 Click this -> :command:`targetName`  # this will always open the first targetName declared in the doc

Goal:

Page-1 Click this -> :command:`targetName <page-1.html#targetName>`  # not working :/
Page-2 Click this -> :command:`targetName <page-2.html#targetName>`  # not working :/
Page-2 Click this -> `targetName <page-2.html#targetName>`_  # this will work but I don't want to use hyperlink instead of " :command: " cuz I want to keep my block style as is.

Solution

  • First some terminology. What you call targetName is called title in reStructuredText. The stuff in angle brackets is the target. See Cross-referencing syntax.

    reStructuredText does not support nested inline markup, which includes styling hyperlinks. However there is a workaround with replacement.

    As reStructuredText doesn't support nested inline markup, the only way to create a reference with styled text is to use substitutions with the "replace" directive:

    I recommend you try |Python|_.
    
    .. |Python| replace:: Python, *the* best language around
    .. _Python: http://www.python.org/
    

    In your case:

    Page-1 Click this -> |myTarget|_
    
    .. |myTarget| replace:: ``targetName``
    .. _myTarget: page-1.html#targetName
    

    For further customization of the appearance, use a custom style. See How do I set up custom styles for reStructuredText, Sphinx, ReadTheDocs, etc.? for one example.