软件简介

Pug(原名 Jade,因商标问题改名)是一个强大、优雅、功能丰富的 Node.js 模板引擎。

Pug 的一般渲染过程很简单,pug.compile()会将 Pug 源码编译成 JavaScript 函数,该 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调用时都会重新编译模板函数,这可能会影响性能。

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>"
转载自: https://www.oschina.net/p/pug