1
0

refactor: 重构外部模板系统,改为单文件模板库模式

主要变更:
- 将 templates_dir 参数改为 template_file,支持单个模板库 YAML 文件
- 添加模板库 YAML 验证功能
- 为模板添加 base_dir 支持,正确解析相对路径资源
- 内联模板与外部模板同名时改为警告(内联优先)
- 移除模板缓存机制,直接使用模板库字典
- 更新所有相关测试以适配新的模板加载方式

此重构简化了模板管理,使模板资源的路径解析更加清晰明确。
This commit is contained in:
2026-03-05 13:26:29 +08:00
parent bd12fce14b
commit f1aae96a04
27 changed files with 2141 additions and 1988 deletions

View File

@@ -74,7 +74,7 @@ slides:
output = temp_dir / "output.pptx"
result = self.run_convert(
str(yaml_path), str(output), "--template-dir", str(sample_template)
str(yaml_path), str(output), "--template", str(sample_template)
)
assert result.returncode == 0
@@ -205,3 +205,68 @@ slides:
else: # 4:3
assert abs(prs.slide_width.inches - 10.0) < 0.01
assert abs(prs.slide_height.inches - 7.5) < 0.01
def test_subdirectory_path_resolution(self, temp_dir):
"""测试子目录中的文件路径解析"""
# 创建子目录结构
doc_dir = temp_dir / "docs"
template_dir = temp_dir / "templates"
doc_dir.mkdir()
template_dir.mkdir()
# 创建模板库文件
template_content = """
templates:
test-template:
vars:
- name: title
required: true
elements:
- type: text
box: [1, 1, 8, 1]
content: "{title}"
"""
template_path = template_dir / "templates.yaml"
template_path.write_text(template_content)
# 创建文档文件
yaml_content = """
metadata:
size: "16:9"
slides:
- template: test-template
vars:
title: "Test Title"
"""
yaml_path = doc_dir / "test.yaml"
yaml_path.write_text(yaml_content)
output_path = temp_dir / "output.pptx"
# 使用相对路径运行转换
import os
original_cwd = os.getcwd()
try:
os.chdir(temp_dir)
result = subprocess.run(
["uv", "run", "python",
str(Path(original_cwd) / "yaml2pptx.py"),
"convert",
"docs/test.yaml",
"output.pptx",
"--template", "templates/templates.yaml"],
capture_output=True,
text=True
)
assert result.returncode == 0, f"转换失败: {result.stderr}"
assert output_path.exists()
# 验证生成的 PPTX
prs = Presentation(str(output_path))
assert len(prs.slides) == 1
text_content = prs.slides[0].shapes[0].text_frame.text
assert "Test Title" in text_content
finally:
os.chdir(original_cwd)