Getting Started

Installation

Pug is available via npm:

  1. $ npm install pug

Overview

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.

  1. //- template.pug
  2. p #{name}'s Pug source code!
  1. const pug = require('pug');
  2. // Compile the source code
  3. const compiledFunction = pug.compileFile('template.pug');
  4. // Render a set of data
  5. console.log(compiledFunction({
  6. name: 'Timothy'
  7. }));
  8. // "<p>Timothy's Pug source code!</p>"
  9. // Render another set of data
  10. console.log(compiledFunction({
  11. name: 'Forbes'
  12. }));
  13. // "<p>Forbes's Pug source code!</p>"

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.

  1. const pug = require('pug');
  2. // Compile template.pug, and render a set of data
  3. console.log(pug.renderFile('template.pug', {
  4. name: 'Timothy'
  5. }));
  6. // "<p>Timothy's Pug source code!</p>"