1
0
Files
PPTX/docs/templates/condition-rendering.md
lanyuanxiaoyao 124ef0e5ce refactor: 重构文档结构,采用渐进式信息披露模式
将 README.md 拆分为多个专题文档,减少认知负荷:
- 用户文档迁移到 docs/ (用户指南、元素、模板、参考等)
- 开发文档迁移到 docs/development/ (架构、模块、规范)
- README.md 精简至 ~290 行,仅保留概览和导航
- 删除 README_DEV.md,内容已迁移
- 归档 OpenSpec 变更 refactor-docs-progressive-disclosure
2026-03-06 15:11:36 +08:00

3.9 KiB
Raw Blame History

条件渲染

条件渲染允许你根据变量值控制元素和幻灯片的显示。

元素级条件渲染

使用 visible 属性控制元素显示,支持强大的条件表达式:

基本示例

# 简单比较
- type: text
  content: "有数据"
  visible: "{count > 0}"

# 字符串比较
- type: text
  content: "草稿状态"
  visible: "{status == 'draft'}"

# 非空检查(向后兼容)
- type: text
  content: "{subtitle}"
  visible: "{subtitle != ''}"

支持的表达式类型

1. 比较运算

==, !=, >, <, >=, <=

visible: "{score >= 60}"
visible: "{price <= 100}"

2. 逻辑运算

and, or, not

visible: "{count > 0 and status == 'active'}"
visible: "{is_draft or is_preview}"
visible: "{not (count == 0)}"

3. 成员测试

in, not in

visible: "{status in ['draft', 'review', 'published']}"
visible: "{level in (1, 2, 3)}"
visible: "{'test' in version}"  # 字符串包含

4. 数学运算

+, -, *, /, %, **

visible: "{(price * discount) > 50}"
visible: "{(total / count) >= 10}"

5. 内置函数

int(), float(), str(), len(), bool(), abs(), min(), max()

visible: "{len(items) > 0}"
visible: "{int(value) > 100}"

复杂条件示例

# 范围检查
- type: text
  content: "评分: {score}"
  visible: "{score >= 60 and score <= 100}"

# 多条件组合
- type: text
  content: "管理员或高分用户"
  visible: "{is_admin or (score >= 90)}"

# 嵌套条件
- type: text
  content: "符合条件"
  visible: "{((count > 0) and (status == 'active')) or (is_admin and (level >= 3))}"

页面级启用控制

使用 enabled 参数控制整个幻灯片是否渲染:

slides:
  # 正常渲染的幻灯片
  - template: title-slide
    vars:
      title: "主标题"

  # 临时禁用的幻灯片(开发调试)
  - enabled: false
    template: work-in-progress
    vars:
      title: "未完成的内容"

  # 继续渲染后续幻灯片
  - template: content-slide
    vars:
      title: "内容页"

enabled 参数说明

  • 类型:布尔值(truefalse
  • 默认值true(未指定时默认启用)
  • 用途:临时禁用幻灯片,无需删除或注释 YAML 内容
  • 场景开发调试、版本控制、A/B 测试

enabled vs visible 的区别

特性 enabled(页面级) visible(元素级)
作用范围 整个幻灯片 单个元素
类型 布尔值 条件表达式
判断时机 加载时(静态) 渲染时(动态)
使用场景 临时禁用页面 条件显示元素

示例

slides:
  # 页面启用,但副标题元素可能隐藏
  - enabled: true
    template: title-slide
    vars:
      title: "标题"
      subtitle: ""  # 空字符串,元素级 visible 会隐藏副标题

  # 整页禁用,不渲染
  - enabled: false
    elements:
      - type: text
        content: "这一页不会出现在最终 PPTX 中"
        box: [1, 1, 8, 1]
        font: {size: 44}

安全策略

条件表达式评估使用 simpleeval 库,具有以下安全限制:

  • 表达式最大长度限制500 字符
  • 禁止属性访问obj.attr
  • 禁止函数定义lambda, def
  • 禁止模块导入import
  • 白名单函数限制

错误处理

常见错误信息:

  • 条件表达式中的变量未定义 - 使用了未在 vars 中定义的变量
  • 条件表达式中使用了不支持的函数 - 使用了白名单之外的函数
  • 条件表达式使用了不支持的语法特性 - 使用了禁止的语法
  • 不支持属性访问 - 尝试访问对象属性
  • 条件表达式语法错误 - 表达式语法有误

相关文档

返回文档索引