简体   繁体   English

使用 Lua 过滤器设置 pandoc 模板变量

[英]Use Lua filter to set pandoc template variable

My goal is to input different text in the template based on a single variable in the yaml.我的目标是根据 yaml 中的单个变量在模板中输入不同的文本。 Below is a minimal attempt, but I can't get it to work.下面是一个最小的尝试,但我无法让它工作。 I'm looking for a Lua filter that set the variable $selected$ based on the value of $switch$ .我正在寻找一个 Lua 过滤器,它根据$switch$的值设置变量$selected$ $ 。 In practice, I'll set several template variables based on that variable.在实践中,我将根据该变量设置几个模板变量。 The idea is to have one more generic template instead of many templates with relative few differences.这个想法是拥有一个更通用的模板,而不是许多差异相对较小的模板。

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

file index.md文件index.md

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

file template.html文件template.html

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

file filter.lua文件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
  }
}

desired output所需 output

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

the result I get我得到的结果

<html>
  <title>alternative</title>
<body>
  <h1></h1>
  <h2>a</h2>
  <p>Some text</p>
</body>
</html>

The issue here is that metadata values look like strings, but can be of some other type.这里的问题是元数据值看起来像字符串,但可以是其他类型。 Here, they are Inlines , as can be checked with this filter:在这里,它们是Inlines ,可以使用此过滤器进行检查:

function Meta (meta)
  print(pandoc.utils.type(meta.switch))
end

The easiest solution is to convert the value to a string with pandoc.utils.stringify :最简单的解决方案是使用pandoc.utils.stringify将值转换为字符串:

    Meta = function(meta)
      meta.selected = choose(pandoc.utils.stringify(meta.switch))
      return meta
    end

The filter should work as expected now.过滤器现在应该可以按预期工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM