[英]Use Lua filter to set pandoc template variable
我的目標是根據 yaml 中的單個變量在模板中輸入不同的文本。 下面是一個最小的嘗試,但我無法讓它工作。 我正在尋找一個 Lua 過濾器,它根據$switch$
的值設置變量$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
}
}
所需 output
<html>
<title>test</title>
<body>
<h1>first choise</h1>
<h2>a</h2>
<p>Some text</p>
</body>
</html>
我得到的結果
<html>
<title>alternative</title>
<body>
<h1></h1>
<h2>a</h2>
<p>Some text</p>
</body>
</html>
這里的問題是元數據值看起來像字符串,但可以是其他類型。 在這里,它們是Inlines ,可以使用此過濾器進行檢查:
function Meta (meta)
print(pandoc.utils.type(meta.switch))
end
最簡單的解決方案是使用pandoc.utils.stringify
將值轉換為字符串:
Meta = function(meta)
meta.selected = choose(pandoc.utils.stringify(meta.switch))
return meta
end
過濾器現在應該可以按預期工作了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.