Sphinx,reStructuredText显示/隐藏代码片段

Ada*_*tan 18 restructuredtext show-hide code-snippets python-sphinx

我一直在使用SphinxreStructuredText记录软件包.

在我的文档中,有一些很长的代码片段.我希望能够将它们隐藏为默认值,并使用一个"显示/隐藏"按钮来扩展它们(示例).

有没有一种标准的方法可以做到这一点?

pba*_*uer 37

您不需要自定义主题.使用内置指令container,允许您向块添加自定义css类并覆盖现有主题以添加一些javascript以添加show/hide功能.

这是_templates/page.html:

{% extends "!page.html" %}

{% block footer %}
 <script type="text/javascript">
    $(document).ready(function() {
        $(".toggle > *").hide();
        $(".toggle .header").show();
        $(".toggle .header").click(function() {
            $(this).parent().children().not(".header").toggle(400);
            $(this).parent().children(".header").toggleClass("open");
        })
    });
</script>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

这是_static/custom.css:

.toggle .header {
    display: block;
    clear: both;
}

.toggle .header:after {
    content: " ?";
}

.toggle .header.open:after {
    content: " ?";
}
Run Code Online (Sandbox Code Playgroud)

现在您可以显示/隐藏代码块.

def setup(app):
    app.add_stylesheet('custom.css')
Run Code Online (Sandbox Code Playgroud)

我在这里使用非常相似的练习:https://training.plone.org/5/mastering_plone/about_mastering.html#exercises

  • 如何使箭头与标题在同一行? (2认同)

Epi*_*ink 19

您可以details通过将代码包装在两个原始 HTML 指令中来使用内置的 HTML 可折叠标签

.. raw:: html

   <details>
   <summary><a>big code</a></summary>

.. code-block:: python

   lots_of_code = "this text block"

.. raw:: html

   </details>
Run Code Online (Sandbox Code Playgroud)

产生:

.. raw:: html

   <details>
   <summary><a>big code</a></summary>

.. code-block:: python

   lots_of_code = "this text block"

.. raw:: html

   </details>
Run Code Online (Sandbox Code Playgroud)

  • 你是我的救星,谢谢 (2认同)

Kev*_*orn 6

我认为最简单的方法是创建一个自定义的Sphinx主题,在其中告诉某些html元素具有此功能.一个小JQuery会在这里走很长的路.

但是,如果您希望能够在reStructuredText标记中指定它,则需要

  • 得到这样的东西包括在狮身人面像本身或
  • 在Sphinx/docutils扩展中实现它...然后创建一个了解此功能的Sphinx主题.

这将是一项更多的工作,但会给你更多的灵活性.

  • 您能否分享您在sphinx文档中为show/hide`工具开发的方式和内容? (2认同)

Mar*_*son 6

有一个非常简单的扩展提供了该功能:https : //github.com/scopatz/hiddencode

它对我来说效果很好。


Phi*_*hil 5

云sphinx主题具有html-toggle提供可切换部分的自定义指令.引用他们的网页:

您可以使用标记部分.. rst-class:: html-toggle,这将使部分默认在html下折叠,并在标题右侧显示"显示部分"切换链接.

是他们的测试演示页面的链接.