如何在Sphinx的LaTeXPDF中用Part/Chapter实现toctree的caption分组
问题描述
我有一个Sphinx文档项目,目录结构如下:
$ tree . ├── _build ├── conf.py ├── index.rst ├── Makefile └── src ├── part1.rst └── part2.rst $
src/part1.rst内容:
Rome ----- Elit provident eum amet in illum Asperiores fugiat voluptatum iste amet nisi! Milan ----- - a - b
src/part2.rst内容:
Paris ------ Dolor ipsa qui beatae officia nesciunt? Similique quia corporis quaerat eligendi itaque? Lyon ----- - a - b
我在index.rst中用:caption实现HTML左侧菜单的内容分组:
Documentation ============== .. toctree:: :maxdepth: 2 :caption: France ./src/part1.rst .. toctree:: :maxdepth: 2 :caption: Italy ./src/part2.rst
但生成LaTeX PDF时,所有章节都处于同一层级:
$ grep "section{" _build/latex/test_toc.tex \section{Rome} \section{Milan} \section{Paris} \section{Lyon}
我需要在LaTeX PDF中保持和HTML一致的分组结构,用part或chapter对法国、意大利内容进行分组。当前使用howto文档类和xelatex,conf.py相关配置:
latex_documents = [('index', 'test_toc.tex', 'Test TOC', 'me', 'howto')]
解决方案
原因说明
howto是Sphinx的轻量级文档类,仅支持section及以下层级,不支持chapter或part,因此无法直接生成分组结构,需要调整文档类并明确标记层级。
步骤1:切换到支持层级的文档类
修改conf.py中的latex_documents配置,将文档类从howto改为manual(manual支持part、chapter等多层级结构):
latex_documents = [('index', 'test_toc.tex', 'Test TOC', 'me', 'manual')]
步骤2:在index.rst中添加层级标记
将原来的:caption替换为Sphinx的层级指令(.. part::或.. chapter::),明确分组的层级,同时保留toctree结构:
Documentation ============== .. part:: France .. toctree:: :maxdepth: 2 ./src/part1.rst .. part:: Italy .. toctree:: :maxdepth: 2 ./src/part2.rst
如果希望用chapter作为分组层级,只需将.. part::替换为.. chapter::即可。
验证结果
重新生成LaTeX PDF后,查看生成的.tex文件,会看到类似以下的层级结构:
\part{France} \section{Rome} \section{Milan} \part{Italy} \section{Paris} \section{Lyon}
这样就实现了和HTML侧边栏一致的分组结构。
内容的提问来源于stack exchange,提问作者user3313834
相关产品推荐
相关产品推荐

