【发布时间】:2011-01-28 02:45:51
【问题描述】:
我一直在使用Sphinx 和reStructuredText 记录一个软件包。
在我的文档中,有一些长代码sn-ps。我希望能够将它们默认隐藏,并带有一个可以展开它们的“显示/隐藏”小按钮 (Example)。
有标准的方法吗?
【问题讨论】:
标签: code-snippets show-hide python-sphinx restructuredtext
我一直在使用Sphinx 和reStructuredText 记录一个软件包。
在我的文档中,有一些长代码sn-ps。我希望能够将它们默认隐藏,并带有一个可以展开它们的“显示/隐藏”小按钮 (Example)。
有标准的方法吗?
【问题讨论】:
标签: code-snippets show-hide python-sphinx restructuredtext
您不需要自定义主题。使用内置指令 container 允许您将自定义 css 类添加到块并覆盖现有主题以添加一些 javascript 以添加显示/隐藏功能。
这是_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 %}
这是_static/custom.css:
.toggle .header {
display: block;
clear: both;
}
.toggle .header:after {
content: " ▶";
}
.toggle .header.open:after {
content: " ▼";
}
这是添加到conf.py:
def setup(app):
app.add_css_file('custom.css')
现在您可以显示/隐藏代码块了。
.. container:: toggle
.. container:: header
**Show/Hide Code**
.. code-block:: xml
:linenos:
from plone import api
...
我在这里使用非常相似的东西来练习:https://training.plone.org/5/mastering-plone/about_mastering.html#exercises
【讨论】:
{% set css_files = css_files + ["_static/custom.css"] %} 导致 Sphinx 警告:RemovedinSphinx20Warning: builder.css_files is deprecated. Please use app.add_stylesheet() instead。请参阅this answer 了解解决方法。
您可以通过将代码包装在两个原始 HTML 指令中来使用内置的 HTML 可折叠 details 标签
.. raw:: html
<details>
<summary><a>big code</a></summary>
.. code-block:: python
lots_of_code = "this text block"
.. raw:: html
</details>
生产:
<details>
<summary><a>big code</a></summary>
<pre>lots_of_code = "this text block"</pre>
</details>
【讨论】:
我认为最简单的方法是创建一个自定义 Sphinx 主题,您可以在其中告诉某些 html 元素具有此功能。一个小小的 JQuery 在这里会大有帮助。
但是,如果您希望能够在 reStructuredText 标记中指定这一点,则需要
这会做更多的工作,但会给你更多的灵活性。
【讨论】:
show/hide 设施开发的方式和内容?
有一个非常简单的扩展提供了该功能:https://github.com/scopatz/hiddencode
它对我来说效果很好。
【讨论】:
由于上述方法似乎都不适合我,所以我最后是这样解决的:
在您的源目录中创建一个文件substitutions.rst,其中包含以下内容:
.. |toggleStart| raw:: html
<details>
<summary><a> the title of the collapse-block </a></summary>
.. |toggleEnd| raw:: html
</details>
<br/>
在您要使用的每个文件的开头添加以下行添加可折叠块
..include:: substitutions.rst
现在,要使部分代码可折叠,只需使用:
|toggleStart|
the text you want to collapse
..code-block:: python
x=1
|toggleEnd|
【讨论】: