How to include an internal reference in a code block?

China☆狼群 提交于 2021-02-07 06:13:13

问题


In my Sphinx .rst document I have a code block containing a tree view of the structure of my product using the UNIX tree command:

  |── parent
  |   |── child
  |       |── grandchild

It's in a code block so that Sphinx preserves the whitespaces.

I want readers to be able to click on each node to follow an internal hyperlink to the part of the document that describes that node. However, adding a :ref: inside the code block doesn't work (see below). Does anyone know how to achieve this?

This doesn't work:

.. _parent:

Parent
------
Blah blah

.. _child:

Child
-----
Blah blah

.. _grandchild:

Grandchild
----------
Blah blah

Then...:

|── :ref:`parent`
|   |── :ref:`child`
|       |── :ref:`grandchild`

回答1:


You can use the parsed-literal directive:

.. parsed-literal:: 

   |── :ref:`parent`
   |   |── :ref:`child`
   |       |── :ref:`grandchild`

This works, but there are warning messages saying "WARNING: Inline substitution_reference start-string without end-string."

The vertical bars are interpreted as parts of substitution references. The warnings go away with some escaping:

.. parsed-literal:: 

   \|── :ref:`parent`
   |   \|── :ref:`child`
   |       \|── :ref:`grandchild`



回答2:


.. code-block:: is for literal code and does not get parsed except for syntax highlighting.

Instead you could use a CSS class my-special-class to apply styles to the tree, and write CSS styles similar to HTML's <pre> or <code>. You will also need to escape | as \| because reST tries to parse | as a substitution.

reST:

.. rst-class:: my-special-class

\|── :ref:`parent`
\|   \|── :ref:`child`
\|       \|── :ref:`grandchild`

CSS:

.my-special-class {
    font-family: monospace;
    white-space: pre;
}


来源:https://stackoverflow.com/questions/44527391/how-to-include-an-internal-reference-in-a-code-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!