You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Lua Filter设置Pandoc模板变量?基于YAML变量动态赋值

问题:基于YAML变量动态设置Pandoc模板变量

场景说明

想通过YAML元数据里的switch变量,用Lua Filter动态设置模板中的selected变量,以此用通用模板替代多个差异极小的模板,但当前实现未达到预期效果。

执行命令

pandoc index.md --to html --from markdown --output index.html --template template.html --lua-filter=filter.lua

相关文件内容

index.md

---
title: "test"
switch: "a"
---
Some text

template.html

<html>
  <title>$title$</title>
  <body>
    <h1>$selected$</h1>
    <h2>$switch$</h2>
    $body$
  </body>
</html>

原错误的filter.lua

local function choose(info)
  local result
  if (info == "a")
  then
    result = "first choise"
  else
    result = "alternative"
  end
  return result
end

return {
  {
    Meta = function(meta)
      meta.title, meta.selected = choose(meta.switch)
      return meta
    end
  }
}

异常现象

期望输出中title保留"test",selected显示"first choise",但实际输出里title被替换成"alternative",selected为空。

错误原因

原Lua代码里的赋值语句meta.title, meta.selected = choose(meta.switch)逻辑错误:choose函数仅返回一个值,这里却试图给两个变量赋值,导致meta.title被覆盖为choose的返回值,meta.selected因无第二个返回值变为nil,模板渲染时就显示为空。

修正后的Lua Filter

修改赋值逻辑,仅给meta.selected赋值,同时修正拼写错误(choise改为choice):

local function choose(info)
  local result
  if info == "a" then
    result = "first choice"
  else
    result = "alternative"
  end
  return result
end

return {
  {
    Meta = function(meta)
      -- 仅设置selected变量,保留原title值
      meta.selected = choose(meta.switch)
      return meta
    end
  }
}

验证结果

修正后执行命令,得到符合预期的输出:

<html>
  <title>test</title>
<body>
  <h1>first choice</h1>
  <h2>a</h2>
  <p>Some text</p>
</body>
</html>

内容的提问来源于stack exchange,提问作者Thierry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:45:13