pythonpython-sphinxrestructuredtext

How to add anchor in list element


I have a list in my rst file that looks like this:

- Item 1
- Item 2
- Item 3

It renders something like the following (which is exactly what I want):

I would like to create links for each item, so I did

.. _item-1:

- Item 1

.. _item-1:

- Item 2

.. _item-1:

- Item 3

Now my list renders something like this:

This is clearly happening because of the anchors I inserted between the elements. Is there a way to insert referenc-able anchors inline in sphinx/rST?


Solution

  • This is pretty close to the desired result, with funky white space.

      .. _item-1:
    
    - Item 1
    
      .. _item-2:
    
    - Item 2
    
      .. _item-3:
    
    - Item 3
    

    This yields the following output. Note the id attribute is on the parent <ul> instead of the first <li>, but effectively resolves to the same location on the page.

    <ul class="simple" id="item-1">
    <li>Item 1</li>
    <li id="item-2">Item 2</li>
    <li id="item-3">Item 3</li>
    </ul>
    

    This can also be done with ennumerated lists.

    Here's a working example in Plone documentation, but in MyST syntax.

    ### Things not to do
    
    The following is a list of the most frequent mistakes made by first-time contributors.
    Learn from their mistakes, and don't commit them yourself.
    
    (mistake-1-label)=
    
    1.  **Never ask to be assigned to an issue.**
        If an issue is claimed—either by assignment, an open pull request, or an explicit comment such as "I am working on this issue"—then it is not available to work on.
        Otherwise, it is available, and you must claim it before you start work on it.
        See {ref}`Avoid duplicate effort <mistake-2-label>`.
        Privileged Plone Team members may ignore or delete comments asking to be assigned to an issue.
    
        (mistake-2-label)=
    
    2.  **Avoid duplicate effort.**
    

    And here are links to those anchors.

    Here are the necessary parts, converted to reStructuredText.

    .. _first-element:
    
    1.  First element
    
        .. _second-element:
    
    1.  Second element
    1.  Third element
    
    
    :ref:`first-element`
    
    :ref:`second-element`
    

    Of course, you'll need enough text following the anchors in the rendered HTML for the page to scroll to the anchor.

    Finally, I recommend 4 spaces for indentation. See https://stackoverflow.com/a/48313531/2214933 and https://stackoverflow.com/a/45683081/2214933 for an explanation.