Sphinx add code formatting to :ref:

2019-08-14 02:15发布

问题:

I would like to add code formatting to a reference like this:

:ref:`__slots__ <python:slots>`

My intersphinx_mapping defines python like this:

intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
}

so the link is to https://docs.python.org/3/reference/datamodel.html#slots (slots is defined in the std:label section of https://docs.python.org/3/objects.inv)

My goal is to format the rendered link in the style of :py:attr: or similar rather than the default text style with which :ref: renders.

None of the following options work:

  • ... ``:ref:`__slots__ <python:slots>``` ... yeilds output like

    ... :ref:`__slots__ <python:slots>` ...

  • ... ``:ref:`__slots__ <python:slots>` `` ... yeilds output like

    ... __slots__ ...

  • ... :ref:```__slots__`` <python:slots>` ... yeilds output like

    ... :ref:```__slots__`` <python:slots>` ...

    There are two separate internal links to #id1 in this case.

  • ... :ref:` ``__slots__`` <python:slots>` ... yeilds output like

    ... :ref:` ``__slots__`` <python:slots>` ...

Relpacing ``...`` with :code:`...` or :literal:`...` either inside or outside the :ref: does not help any either. In fact, it appears that nested roles are not allowed at all.

I would like to have an inline role that results in something that renders with a code style and a link, like

... __slots__ ...

How do I get the basic :ref: (or equivalent) to appear with the code-style formatting used by :py:attr:?

I am using Sphinx 1.6.3 with Python 3.6.2 in an Anaconda environment.

Inverse question is here: Sphinx remove code formatting from custom code reference

A tangentially relevant question: Nested / Compounded roles: apply multiple roles to overlapping text

回答1:

The :any: role does what you want:

:any:`__slots__ <python:slots>`

This is a "convenience role" that looks for cross-reference targets in the current domain as well as targets that work with :ref:.

The Python domain has several specific cross-reference roles, for different types of objects.