# 外部模板库 外部模板库是一个包含多个模板的 YAML 文件,适合跨文档复用和团队共享。 ## 创建模板库文件 创建模板库文件 `templates.yaml`: ```yaml # 模板库元数据(必需) metadata: size: "16:9" # 必需:模板库尺寸,必须与使用它的文档一致 description: "公司标准模板库" # 可选:描述信息 fonts: # 可选:模板库字体主题 template-title: family: "cjk-sans" size: 44 bold: true color: "#2c3e50" template-body: family: "sans" size: 20 color: "#34495e" fonts_default: "@template-body" # 可选:模板库默认字体 # 模板定义(必需) templates: title-slide: description: "标题页模板" vars: - name: title required: true - name: subtitle required: false default: "" elements: - type: text box: [1, 2, 8, 1] content: "{title}" font: "@template-title" # 引用模板库字体 - type: text box: [1, 3.5, 8, 0.5] content: "{subtitle}" visible: "{subtitle != ''}" font: parent: "@template-title" size: 24 align: center content-slide: description: "内容页模板" vars: - name: title required: true - name: content required: true elements: - type: text box: [1, 1, 8, 0.8] content: "{title}" font: parent: "@template-title" size: 32 - type: text box: [1, 2, 8, 3] content: "{content}" # 未指定 font 时使用 fonts_default ``` ## 重要说明 ### 1. metadata 字段是必需的 - `metadata.size` 必须指定("16:9" 或 "4:3") - 模板库的 size 必须与使用它的文档 size 一致,否则会报错 ### 2. 字体主题系统 - 模板库可以定义自己的字体主题(`metadata.fonts`) - 文档可以引用模板库的字体(跨域引用) - 模板库不能引用文档的字体(单向引用) - 模板库的 `fonts_default` 只能引用模板库内部字体 ### 3. 字体级联规则 - 模板元素未指定字体时,使用模板库的 `fonts_default` - 如果模板库没有 `fonts_default`,使用文档的 `fonts_default` - 如果都没有,使用系统默认字体 ## 使用外部模板库 在命令行中指定模板库文件: ```bash uv run yaml2pptx.py convert presentation.yaml output.pptx --template ./templates.yaml ``` 在 YAML 文件中引用模板: ```yaml slides: - template: title-slide vars: title: "我的演示文稿" subtitle: "使用外部模板库" - template: content-slide vars: title: "第一章" content: "这是内容" ``` ## 模板库特性 - 单个文件包含多个模板 - 支持模板库元数据(description、version、author) - 每个模板可以有独立的 description - 便于版本控制和分发 - 支持相对路径的图片资源(相对于模板库文件所在目录) ## 模板库文件结构 ```yaml # 顶层元数据(可选) description: "模板库描述" version: "版本号" author: "作者" # 模板定义(必需) templates: 模板名称1: description: "模板描述(可选)" vars: [...] elements: [...] 模板名称2: description: "模板描述(可选)" vars: [...] elements: [...] ``` ## 模板 description 字段 模板可以包含可选的 `description` 字段,用于描述模板的用途和设计意图: ```yaml templates: title-slide: description: "用于章节标题页的模板,包含主标题和副标题" vars: - name: title required: true elements: - type: text box: [1, 2, 8, 1] content: "{title}" font: size: 44 bold: true ``` ## 资源路径解析 模板库中的图片资源使用相对于模板库文件所在目录的路径: ```yaml # templates.yaml 所在目录:/path/to/templates/ templates: logo-slide: elements: - type: image src: "images/logo.png" # 相对于 templates.yaml 所在目录 box: [1, 1, 2, 2] ``` ## 与内联模板的对比 | 特性 | 内联模板 | 外部模板库 | |------|---------|-----------| | 定义位置 | 源文件中 | 独立文件 | | 适用场景 | 单文档使用 | 跨文档复用 | | 命令行参数 | 无需 | 需要 `--template` | | 模板间引用 | 不支持 | 支持 | | 字体主题 | 使用文档字体 | 可定义独立字体 | ## 相关文档 - [内联模板](inline.md) - 在源文件中定义模板 - [混合模式](mixing-mode.md) - 模板与自定义元素组合 - [字体主题系统](../fonts.md) - 字体配置和跨域引用 [返回文档索引](../README.md)