【问题标题】:Does pandoc support creation of markdown tables in its templates?pandoc 是否支持在其模板中创建降价表?
【发布时间】:2019-05-05 07:01:59
【问题描述】:

我正在阅读 pandoc 手册,如果我理解正确,它支持使用模板文件和包含要在模板中使用的变量的 YAML 文件。 它还说 YAML 支持任意对象(甚至列表)。但是,我想问是否可以使用 YAML 数据在模板中呈现降价表。 这些示例仅显示了一个简单的键和值映射。


编辑: 我创建了一个包含这个的 testable.md 文件

---
table:
  caption: Cities
  headers: [city, population]
  rows:
    - [Berlin, '3,748,148']
    - [Tokyo, '13,839,910']
---

$table$

**Random Text**

并使用此命令来使用 tarleb 提供的过滤器: pandoc -f markdown -t docx --lua-filter=yaml_table.lua -o target.docx testtable.md

但是,输出文件似乎仍然不包含该表。 我错过了什么吗?


编辑: 我意识到模板文件的指定与输入不同 当我将 testtable.md 设置为仅包含以下内容时,它可以正常工作:

---
table:
  caption: Cities
  headers: [city, population]
  rows:
    - [Berlin, '3,748,148']
    - [Tokyo, '13,839,910']
---

并创建了一个名为 markdowntmpl.md 的模板文件,其中包含以下内容

$table$

**Random Text**

然后我使用了以下命令:

pandoc -f markdown -t markdown --template=markdowntemplate.md --lua-filter=yaml_table.lua -o target.md testtable.md

输出:

  city     population
  -------- ------------
  Berlin   3,748,148
  Tokyo    13,839,910

  : Cities

**Random Text**

然后我可以继续用它创建一个 docx 文档。

【问题讨论】:

  • 如果你能找到 YAML 支持的数据类型,它包含表格数据,那么你应该能够使用该数据来构建表格。但我不知道有任何 YAML 支持的数据类型。

标签: markdown pandoc


【解决方案1】:

Markdown 中可表示的所有元素也可以放入元数据字段中。插入复杂元素的最简单方法是对多行字符串使用保留换行符的 YAML 语法。例如,

---
table: |
  | city   | population |
  |--------|------------|
  | Berlin |  3,748,148 |
  | Tokyo  | 13,839,910 |
---

这将table 定义为包含表格的元数据字段。


没有定义表格的“原生”YAML 方式,但您可以使用 pandoc Lua filter 自行滚动。

假设有人想这样定义一个表:

---
table:
  caption: Cities
  headers: [city, population]
  rows:
    - [Berlin, '3,748,148']
    - [Tokyo, '13,839,910']
---

那么就可以使用下面的过滤器将其转换成pandoc表了。

local List = require 'pandoc.List'

function repeated(item, times)
  local result = {}
  for i = 1, times do result[i] = item end
  return result
end

function to_table (tbl)
  if tbl.t ~= 'MetaMap' or not tbl.rows then
    return nil
  end

  -- Turn MetaInlines into blocks
  local to_blocks = function (x) return {pandoc.Plain(List:new(x))} end

  local headers = (List:new(tbl.headers)):map(to_blocks)
  local rows = List:new(tbl.rows):map(
    function (row) return List:new(row):map(to_blocks) end
  )
  local columns = #rows[1]
  local aligns = tbl.aligns or repeated(pandoc.AlignDefault, columns)
  local widths = tbl.widths or repeated(0, columns)
  return pandoc.Table(List:new(tbl.caption), aligns, widths, headers, rows)
end

function Meta (meta)
  for k, v in pairs(meta) do
      local success, result = pcall(to_table, v)
      if success and result then
        meta[k] = pandoc.MetaBlocks{result}
      end
  end
  return meta
end

【讨论】:

  • 这很好。我在想一个 YAML 2D Array --- table: [[Name, Address],[Alice, Wonderland],[Batman, Gotham]] --- 我想知道是否可以在 markdown
  • ☝️你去。
  • 感谢 lua 过滤器参考!我想我需要先研究一下这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多