入门
安装
Pug 可通过 npm 获得:
$ npm install pug
概述
Pug 的总体渲染过程很简单。pug.compile()
会将
Pug 源代码编译为 JavaScript 函数,该函数采用数据对象(称为“locals
”)作为参数。使用你的数据调用该结果函数,瞧!,它将返回一个使用你的数据渲染的 HTML
字符串。
编译后的函数可以重复使用,并可以使用不同的数据集进行调用。
//- template.pug
p #{name}'s Pug source code!
const pug = require('pug');
// Compile the source code
const compiledFunction = pug.compileFile('template.pug');
// Render a set of data
console.log(compiledFunction({
name: 'Timothy'
}));
// "<p>Timothy's Pug source code!</p>"
// Render another set of data
console.log(compiledFunction({
name: 'Forbes'
}));
// "<p>Forbes's Pug source code!</p>"
Pug 还提供了 pug.render()
系列函数,将编译和渲染合并为一个步骤。但是,每次调用 render
时都会重新编译模板函数,这可能会影响性能。或者,你可以将
cache
选项与 render
一起使用,这将自动将编译后的函数存储到内部缓存中。
const pug = require('pug');
// Compile template.pug, and render a set of data
console.log(pug.renderFile('template.pug', {
name: 'Timothy'
}));
// "<p>Timothy's Pug source code!</p>"