如何在Sphinx autoclass模板中条件检查文件是否存在?
问题:在Sphinx autoclass模板中条件引入Graphviz文件
我需要在Sphinx的autoclass模板中实现:仅当对应类的Graphviz .dot 文件存在时,才引入该文件(只有部分类对象配有这类文件)。
最初尝试的模板代码:
{% if hasdoc('./../lib/program_data.{{ objname }}.dot') %} .. graphviz:: ../../lib/program_data.{{ objname }}.dot {% endif %}
但运行后报错:
Extension error (sphinx.ext.autosummary): Handler <function process_generate_options at 0x7f8eb92a3880> for event 'builder-inited' threw an exception (exception: 'hasdoc' is undefined)
hasdoc是Sphinx官方文档列出的模板辅助函数,但在autoclass模板环境中无法使用;尝试直接调用os.path.exists(),又会提示os未定义。
解决方案
1. 在conf.py中添加自定义上下文函数
在Sphinx配置文件conf.py里,通过setup函数注入一个文件存在性检查的工具函数:
import os from sphinx.util import path as sphinx_path def setup(app): def inject_file_checker(app): def file_exists(rel_path): # 转换为Sphinx源目录下的绝对路径 abs_file_path = os.path.join(app.srcdir, rel_path) # 使用Sphinx的路径工具保证跨平台兼容性 return sphinx_path.exists(abs_file_path) # 将函数添加到模板全局上下文 app.config.html_context['file_exists'] = file_exists # 在构建器初始化完成后注入上下文 app.connect('builder-inited', inject_file_checker)
2. 修改autoclass模板代码
在你的autoclass模板中,使用自定义的file_exists函数进行判断,同时用Jinja的字符串拼接语法替代嵌套模板变量:
{% if file_exists('../../lib/program_data.' ~ objname ~ '.dot') %} .. graphviz:: ../../lib/program_data.{{ objname }}.dot {% endif %}
3. 路径说明
- 传入
file_exists的路径是**相对于Sphinx源目录(srcdir)**的相对路径,确保路径解析的准确性 - 如果
.dot文件位于Sphinx项目目录外,需保证Sphinx进程有该文件的读取权限
内容的提问来源于stack exchange,提问作者Pete Reiter
相关产品推荐
相关产品推荐

