入门(Getting Started)

¥Getting Started

安装(Installation)

¥Installation

Pug 可通过 npm 获得:

¥Pug is available via npm:

$ npm install pug

概述(Overview)

¥Overview

Pug 的总体渲染过程很简单。pug.compile() 会将 Pug 源代码编译为 JavaScript 函数,该函数采用数据对象(称为“locals”)作为参数。使用你的数据调用该结果函数,瞧!,它将返回一个使用你的数据渲染的 HTML 字符串。

¥The general rendering process of Pug is simple. pug.compile() will compile the Pug source code into a JavaScript function that takes a data object (called “locals”) as an argument. Call that resultant function with your data, and voilà!, it will return a string of HTML rendered with your data.

编译后的函数可以重复使用,并可以使用不同的数据集进行调用。

¥The compiled function can be re-used, and called with different sets of data.

//- 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 一起使用,这将自动将编译后的函数存储到内部缓存中。

¥Pug also provides the pug.render() family of functions that combine compiling and rendering into one step. However, the template function will be re-compiled every time render is called, which might impact performance. Alternatively, you can use the cache option with render, which will automatically store the compiled function into an internal cache.

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>"
Pug 中文网 - 粤ICP备13048890号