快速浏览

Asciidoctor.js 是一个 快速 的文本处理器,用于将 AsciiDoc 内容转换为 HTML5、幻灯片和其他格式。本快速浏览将为您提供如何将 AsciiDoc 内容转换为 HTML5 的概述。

第一次转换

首先,您需要实例化 Asciidoctor.js 以获得一个 处理器

var asciidoctor = Asciidoctor()

要转换一个 AsciiDoc 格式的字符串:

var html = asciidoctor.convert('Hello, _Asciidoctor_')
console.log(html)
// <div class="paragraph">
// <p>Hello, <em>Asciidoctor</em></p>
// </div>

在转换字符串时,默认情况下会排除头部和尾部,以使 Asciidoctor 与其他轻量级标记引擎(如 Markdown)保持一致。如果您希望生成一个独立的文档,可以通过 standalone 选项启用:

var html = asciidoctor.convert('*This* is Asciidoctor.', { standalone: true })

另外,您可以使用 convertFile 函数将包含 AsciiDoc 标记的文件转换为 HTML5:

var doc = asciidoctor.convertFile('/path/to/file.adoc') (1)
1 该命令将输出到相同目录中的 file.html 文件。变量 doc 将包含一个 Asciidoctor.Document 对象。

或者,您可以将 HTML5 输出捕获到一个变量中,而不是写入文件:

var html = asciidoctor.convertFile('/path/to/file.adoc', { to_file: false, standalone: true })

如上所示,convert 函数接受一个可选的参数来指定选项。 有关此参数的使用,请参见 Convert options 部分

如果您使用的是 Node.js,您还可以使用 Buffer

var html = asciidoctor.convert(fs.readFileSync('/path/to/file.adoc')) (1)
1 readFileSync 会返回一个 Buffernodejs.org/api/fs.html#fs_fs_readfilesync_path_options

加载并转换

要将一个 AsciiDoc 文件解析为一个 Asciidoctor.Document 对象:

var doc = asciidoctor.loadFile('file.adoc')

您可以获取关于文档的信息:

console.log(doc.getDocumentTitle())
console.log(doc.getAttributes())

很可能,您将希望转换文档。要将一个 Asciidoctor.Document 转换为 HTML5,可以在文档上使用 convert 函数:

var doc = asciidoctor.loadFile('file.adoc')
doc.convert()

与 convert 函数一样,也可以加载一个 AsciiDoc 格式的 字符串Buffer

var doc = asciidoctor.load('Hello, _Asciidoctor_')
var doc = asciidoctor.load(fs.readFileSync('/path/to/file.adoc'))

使用 CSS 样式化 HTML

Asciidoctor.js 使用 CSS 来进行 HTML 文档样式化。它捆绑了一个样式表,名为 asciidoctor.css

默认样式表位于 node_modules/asciidoctor.js/dist/css/asciidoctor.css

当您使用 Node.js 生成文档时,默认情况下,asciidoctor.css 样式表会嵌入到 HTML 输出中(当安全模式小于 secure 时)。

asciidoctor.convertFile('/path/to/file.adoc', { safe: 'safe' })

要使文档链接到样式表,可以设置 linkcss 属性:

asciidoctor.convertFile('/path/to/file.adoc', { safe: 'safe', attributes: { linkcss: true } })