我想做的是写一个包含课堂练习问题和答案的降价文件。 在文件的元数据部分,我想定义一个变量
render-solution
。在文件的主体中,解决方案将以某种方式包含在自定义定义的 div 部分中。
像这样的东西:
---
title: My Document
render-solution: yes
---
## Task 1
A difficult problem
::: { .conditional-render }
## Solution 1
Here is the solution
:::
然后自定义过滤器将检查
render-solution
变量的值,如果值为 yes
,则呈现自定义 div 部分(包含解决方案)的内容。如果变量的值为no
,则不渲染div部分的内容。
我很确定,这可以用 pandoc 过滤器来完成,但我无法让它工作。
我尝试了以下 pandoc 过滤器
#!/usr/bin/env python
from pandocfilters import toJSONFilter, Str, Para, Div
def conditional_render(key, value, format, meta):
if key == 'Div':
[[ident, classes, kvs], content] = value
if 'conditional-render' in classes:
if meta['render-solution']['c'] == "yes":
return Div([ident, classes, kvs], content)
else:
return []
if __name__ == "__main__":
toJSONFilter(conditional_render)
但是没用。该部分不会独立于
render-solution
的值而呈现
我这里用的是Lua filter,因为Lua是内置的,filter在手头的情况下比较短:
function Pandoc (doc)
local render_solutions = doc.meta['render-solutions']
return doc:walk {
Div = function (div)
if div.classes:includes 'conditional-render' then
return render_solutions and
div.content or -- unwrap the div, just return the contents
{} -- otherwise return an empty list of elements
end
end
}
end
walk
函数基本上是一个过滤器中的过滤器。需要额外的复杂性,因为我们首先需要从元数据中获取值。
感谢@tarleb 的 lua 过滤器。 与此同时,我想出了一个不是很好的解决方案,我可以使用它直到我理解其余部分。
---
title: "A test file"
render-solutions: "yes"
---
## Task 1
A difficult question
::: solution_yes
## Solution
This is the solution
:::
然后我可以使用一个简单的过滤器
#!/usr/bin/env python
from pandocfilters import toJSONFilter, Str, Para, Div
def conditional_render(key, value, format, meta):
if key == 'Div' :
[[ident, classes, kvs], content] = value
if 'solution_yes' in classes:
return Div([ident, classes, kvs], content)
else:
return []
if __name__ == "__main__":
toJSONFilter(conditional_render)
这行得通,但是当我不想呈现解决方案时,我必须将所有 div 从
solution_yes
更改为其他内容。效率不高且容易出错。
问题是我仍然不知道如何正确访问元部分的内容。当然,我还是不懂lua。