1

Hi whoever will read this!

I am writing a documentation webpage with Sphinx, and though I have been able to create nice cross-referencing in the same page following what is found on this guide, I now want to add in page A the reference to a subsection in page B.

I know that I can do so with an explicit external link, like:

`Link name <https://my.documentation.domain/path/to/page-B#subsection>`_

but can I do so with a cross-reference as well? It would be neater in my opinion. I tried :

:doc:`page_B:subsection`

and

:doc:`page_B#subsection`

but it is not recognized. Sorry if this is a dummy question but I did not find the answer on the internet. Thank you :)

jeannej
  • 1,135
  • 1
  • 9
  • 23
  • 1
    [This answer](https://stackoverflow.com/a/19543591) is likely what you're looking for, it's what's called [arbitrary location](https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#cross-referencing-arbitrary-locations) in the documentation. – bad_coder Nov 17 '22 at 00:22

1 Answers1

1

Thank you @bad_coder and @Steve Piercy! So this question's answer is what I was looking for, but was not formulated in a way I could find it. For anyone who would end up here, what worked for me is :

Define a target in page-A, by adding before the section title:

.. _target name in page A:

Refer to this target in page-B, simply with:

:ref:`target name in page A`

Note that you do not need to add page-A name, the reference will be automatically found.

It also works to use a relative html link, but this is far less robust (it would break if section names are changing, for instance):

`Link name <page_A.html#subsection>`_
jeannej
  • 1,135
  • 1
  • 9
  • 23
  • 1
    This isn't the optimal solution, when writing reST links for your docs internally it's always possible to avoid writing the anchor (in your example the `#subsection` portion of the link target). It's preferable to avoid writing anchors and just use target names (as shown in the other post) because if you decide to refactor or move something the URL and the anchor will change, the aim of using a link target name is avoiding the additional maintenance/breakage that explicit anchors (like in your answer) will cause down the road. – bad_coder Nov 21 '22 at 12:00
  • 1
    IOW, instead of `` (e.g. ``) go for `` in the link. – bad_coder Nov 21 '22 at 12:10
  • 1
    @bad_coder thank you for your input! That is very cool, I did not understand that targets worked across files (I was a bit fast to jump to the second half of the answer). I will update mine then :) – jeannej Nov 21 '22 at 19:26