pug Documentation

Pug – robust, elegant, feature rich template engine for Node.js

21,828 stars JavaScript JavaScript 1 file · ~11,308 tokens
RAW Doc

Technical Documentation: pugjs/pug

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

Pug

Full documentation is at pugjs.org

Pug is a high-performance template engine heavily influenced by Haml
and implemented with JavaScript for Node.js and browsers. For bug reports,
feature requests and questions, open an issue.
For discussion join the chat room.

You can test drive Pug online here.

Professionally supported pug is now available




Packages

Package Name Version
pug
pug-attrs
pug-code-gen
pug-error
pug-filters
pug-lexer
pug-linker
pug-load
pug-parser
pug-runtime
pug-strip-comments
pug-walk

Rename from "Jade"

This project was formerly known as "Jade". However, it was revealed to us that "Jade" is a registered trademark; as a result, a rename was needed. After some discussion among the maintainers, "Pug" was chosen as the new name for this project. As of version 2, "pug" is the official package name.

If your package or app currently uses jade, don't worry: we have secured permissions to continue to occupy that package name, although all new versions will be released under pug.

Before the renaming, work had already begun on “Jade 2.0.0”. Therefore, the rename to Pug coincided with the major version bump. As a result, upgrading from Jade to Pug will be the same process as upgrading any other package with a major version bump.

The syntax of Pug has several differences, deprecations, and removals compared to its predecessor. These differences are documented in #2305.

The website and documentation for Pug are still being updated. But if you are new to Pug, you should get started with the new syntax and install the Pug package from npm.

Installation

Package

To use Pug in your own JavaScript projects:

bash
$ npm install pug

Command Line

After installing the latest version of Node.js, install with:

bash
$ npm install pug-cli -g

and run with

bash
$ pug --help

Syntax

Pug is a clean, whitespace sensitive syntax for writing HTML. Here is a simple example:

pug
doctype html
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) bar(1 + 5);
  body
    h1 Pug - node template engine
    #container.col
      if youAreUsingPug
        p You are amazing
      else
        p Get on it!
      p.
        Pug is a terse and simple templating language with a
        strong focus on performance and powerful features.

Pug transforms the above to:

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pug</title>
    <script type="text/javascript">
      if (foo) bar(1 + 5);
    </script>
  </head>
  <body>
    <h1>Pug - node template engine</h1>
    <div id="container" class="col">
      <p>You are amazing</p>
      <p>
        Pug is a terse and simple templating language with a strong focus on
        performance and powerful features.
      </p>
    </div>
  </body>
</html>

API

For full API, see pugjs.org/api/reference.html

js
var pug = require('pug');

// compile
var fn = pug.compile('string of pug', options);
var html = fn(locals);

// render
var html = pug.render('string of pug', merge(options, locals));

// renderFile
var html = pug.renderFile('filename.pug', merge(options, locals));

Options

  • filename Used in exceptions, and required when using includes
  • compileDebug When false no debug instrumentation is compiled
  • pretty Add pretty-indentation whitespace to output (false by default)

Browser Support

The latest version of pug can be downloaded for the browser in standalone form. It only supports the very latest browsers, though, and is a large file. It is recommended that you pre-compile your pug templates to JavaScript.

To compile a template for use on the client using the command line, do:

bash
$ pug --client --no-debug filename.pug

which will produce filename.js containing the compiled template.

Tutorials

Implementations in other languages

Ports in other languages

Ports to other languages, with very close syntax:

Equivalents in other languages

Templates engines for other languages with a different syntax, but a similar philosophy:

Framework implementations/adapters

Embedded view engines for frameworks:

CMS plugins

Additional Resources

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]






























Sponsors

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]






























License

MIT


Overview (`packages/pug-attrs/README.md`)

pug-attrs

Generate code for Pug attributes



Installation

text
npm install pug-attrs

Usage

js
var compileAttrs = require('pug-attrs');

`compileAttrs(attrs, options)`

Compile attrs to a JavaScript string that evaluates to the attributes in the desired format.

options MUST include the following properties:

  • terse: whether or not to use HTML5-style terse boolean attributes
  • runtime: callback that takes a runtime function name and returns the source code that will evaluate to that function at runtime
  • format: output format; must be html or object

attrs is an array of attributes, with each attribute having the form of { name, val, mustEscape }. val represents a JavaScript string that evaluates to the value of the attribute, either statically or dynamically.

js
var compileAttrs = require('pug-attrs');
var pugRuntime = require('pug-runtime');

function getBaz () { return 'baz<>'; }

var attrs = [
  {name: 'foo',  val: '"bar"',    mustEscape: true },
  {name: 'baz',  val: 'getBaz()', mustEscape: true },
  {name: 'quux', val: true,       mustEscape: false}
];
var result, finalResult;

// HTML MODE
result = compileAttrs(attrs, {
  terse:   true,
  format:  'html',
  runtime: function (name) { return 'pugRuntime.' + name; }
});
//=> '" foo=\\"bar\\"" + pugRuntime.attr("baz", getBaz(), true, true) + " quux"'

finalResult = Function('pugRuntime, getBaz',
  'return (' + result + ');'
);
finalResult(pugRuntime, getBaz);
// => ' foo="bar" baz="baz&lt;&gt;" quux'

// OBJECT MODE
result = compileAttrs(attrs, {
  terse:   true,
  format:  'object',
  runtime: function (name) { return 'pugRuntime.' + name; }
});
//=> '{"foo": "bar","baz": pugRuntime.escape(getBaz()),"quux": true}'

finalResult = Function('pugRuntime, getBaz',
  'return (' + result + ');'
);
finalResult(pugRuntime, getBaz);
//=> { foo: 'bar', baz: 'baz&lt;&gt;', quux: true }

License

MIT


Overview (`packages/pug-code-gen/README.md`)

pug-code-gen

Default code-generator for pug. It generates HTML via a JavaScript template function.


Installation

text
npm install pug-code-gen

Usage

js
var generateCode = require('pug-code-gen');

`generateCode(ast, options)`

Generate a JavaScript function string for the given AST.

ast is a fully expanded AST for Pug, with all inclusion, extends, and filters resolved.

options may contain the following properties that have the same meaning as the options with the same names in pug:

  • pretty (boolean): default is false
  • compileDebug (boolean): default is true
  • doctype (string): default is undefined
  • inlineRuntimeFunctions (boolean): default is false
  • globals (array of strings): default is []
  • self (boolean): default is false

In addition to above, pug-code-gen has the following unique options:

  • includeSources (object): map of filename to source string; used if compileDebug is true; default is undefined
  • templateName (string): the name of the generated function; default is 'template'
js
var lex = require('pug-lexer');
var parse = require('pug-parser');
var wrap = require('pug-runtime/wrap');
var generateCode = require('pug-code-gen');

var funcStr = generateCode(parse(lex('p Hello world!')), {
  compileDebug: false,
  pretty: true,
  inlineRuntimeFunctions: false,
  templateName: 'helloWorld'
});
//=> 'function helloWorld(locals) { ... }'

var func = wrap(funcStr, 'helloWorld');
func();
//=> '\n<p>Hello world!</p>'

`new generateCode.CodeGenerator(ast, options)`

The constructor for the internal class of the code generator. You shouldn't need to use this for most purposes.

License

MIT


Overview (`packages/pug-error/README.md`)

pug-error

Standard error objects for pug. This module is intended for use by the lexer, parser, loader, linker, code-generator and any plugins.



Installation

text
npm install pug-error

Usage

js
var error = require('pug-error');

`error(code, message, options)`

Create a Pug error object.

code is a required unique code for the error type that can be used to pinpoint a certain error.

message is a human-readable explanation of the error.

options can contain any of the following properties:

  • filename: the name of the file causing the error
  • line: the offending line
  • column: the offending column
  • src: the Pug source, if available, for pretty-printing the error context

The resulting error object is a simple Error object with additional properties given in the arguments.

Caveat: the message argument is stored in err.msg, not err.message, which is occupied with a better-formatted message.

js
var error = require('pug-error');

var err = error('MY_CODE', 'My message', {line: 3, filename: 'myfile', src: 'foo\nbar\nbaz\nbash\nbing'});
// { code: 'PUG:MY_CODE',
//   msg: 'My message',
//   line: 3,
//   column: undefined,
//   filename: 'myfile',
//   src: 'foo\nbar\nbaz\nbash\nbing',
//   message: 'myfile:3\n    1| foo\n    2| bar\n  > 3| baz\n    4| bash\n    5| bing\n\nMy message' }

throw err;

License

MIT


Overview (`packages/pug-filters/README.md`)

pug-filters

Code for processing filters in pug templates




Installation

text
npm install pug-filters

Usage

text
var filters = require('pug-filters');

`filters.handleFilters(ast, filters)`

Renders all Filter nodes in a Pug AST (ast), using user-specified filters (filters) or a JSTransformer.

`filters.runFilter(name, str[, options[, currentDirectory]])`

Invokes filter through jstransformer.

This is internally used in filters.handleFilters, and is a lower-level interface exclusively for invoking JSTransformer-based filters.

name represents the name of the JSTransformer.

str represents the string to render.

currentDirectory is used when attempting to require the transformer module.

options may contain the following properties:

  • minify (boolean): whether or not to attempt minifying the result from the transformer. If minification fails, the original result is returned.

License

MIT


Overview (`packages/pug-lexer/README.md`)

pug-lexer

The pug lexer. This module is responsible for taking a string and converting it into an array of tokens.





Installation

text
npm install pug-lexer

Usage

js
var lex = require('pug-lexer');

`lex(str, options)`

Convert Pug string to an array of tokens.

options can contain the following properties:

  • filename (string): The name of the Pug file; it is used in error handling if provided.
  • plugins (array): An array of plugins, in the order they should be applied.
js
console.log(JSON.stringify(lex('div(data-foo="bar")', {filename: 'my-file.pug'}), null, '  '))
json
[
  {
    "type": "tag",
    "line": 1,
    "val": "div",
    "selfClosing": false
  },
  {
    "type": "attrs",
    "line": 1,
    "attrs": [
      {
        "name": "data-foo",
        "val": "\"bar\"",
        "escaped": true
      }
    ]
  },
  {
    "type": "eos",
    "line": 1
  }
]

`new lex.Lexer(str, options)`

Constructor for a Lexer class. This is not meant to be used directly unless you know what you are doing.

options may contain the following properties:

  • filename (string): The name of the Pug file; it is used in error handling if provided.
  • interpolated (boolean): if the Lexer is created as a child lexer for inline tag interpolation (e.g. #[p Hello]). Defaults to false.
  • startingLine (integer): the real line number of the first line in the input. It is also used for inline tag interpolation. Defaults to 1.
  • plugins (array): An array of plugins, in the order they should be applied.

License

MIT


Overview (`packages/pug-linker/README.md`)

pug-linker

Link multiple pug ASTs together using include/extends




Installation

text
npm install pug-linker

Usage

js
var link = require('pug-linker');

Flatten the Pug AST of inclusion and inheritance.

This function merely links the AST together; it doesn't read the file system to resolve and parse included and extended files. Thus, the main AST must already have the ASTs of the included and extended files embedded in the FileReference nodes. pug-load is designed to do that.

License

MIT


Overview (`packages/pug-load/README.md`)

pug-load

The pug loader is responsible for loading the depenendencies of a given pug file. It adds fullPath and str properties to every Include and Extends node. It also adds an ast property to any Include nodes that are loading pug and any Extends nodes. It then recursively loads the dependencies of any of those included files.





Installation

text
npm install pug-load

Usage

js
var load = require('pug-load');

`load(ast, options)`

`load.string(str, filename, options)`

`load.file(filename, options)`

Loads all dependencies of the Pug AST. load.string and load.file are syntactic sugar that parses the string or file instead of you doing it yourself.

options may contain the following properties:

  • lex (function): (required) the lexer used
  • parse (function): (required) the parser used
  • resolve (function): a function used to override load.resolve. Defaults to load.resolve.
  • read (function): a function used to override load.read. Defaults to load.read.
  • basedir (string): the base directory of absolute inclusion. This is required when absolute inclusion (file name starts with '/') is used. Defaults to undefined.

The options object is passed to load.resolve and load.read, or equivalently options.resolve and options.read.

`load.resolve(filename, source, options)`

Callback used by pug-load to resolve the full path of an included or extended file given the path of the source file.

filename is the included file. source is the name of the parent file that includes filename.

This function is not meant to be called from outside of pug-load, but rather for you to override.

`load.read(filename, options)`

Callback used by pug-load to return the contents of a file.

filename is the file to read.

This function is not meant to be called from outside of pug-load, but rather for you to override.

`load.validateOptions(options)`

Callback used pug-load to ensure the options object is valid. If your overridden load.resolve or load.read uses a different options scheme, you will need to override this function as well.

This function is not meant to be called from outside of pug-load, but rather for you to override.

Example

js
var fs = require('fs');
var lex = require('pug-lexer');
var parse = require('pug-parser');
var load = require('pug-load');

// you can do everything very manually

var str = fs.readFileSync('bar.pug', 'utf8');
var ast = load(parse(lex(str, 'bar.pug'), 'bar.pug'), {
  lex: lex,
  parse: parse,
  resolve: function (filename, source, options) {
    console.log('"' + filename + '" file requested from "' + source + '".');
    return load.resolve(filename, source, options);
  }
});

// or you can do all that in just two steps

var str = fs.readFileSync('bar.pug', 'utf8');
var ast = load.string(str, 'bar.pug', {
  lex: lex,
  parse: parse,
  resolve: function (filename, source, options) {
    console.log('"' + filename + '" file requested from "' + source + '".');
    return load.resolve(filename, source, options);
  }
});

// or you can do all that in only one step

var ast = load.file('bar.pug', {
  lex: lex,
  parse: parse,
  resolve: function (filename, source, options) {
    console.log('"' + filename + '" file requested from "' + source + '".');
    return load.resolve(filename, source, options);
  }
});

License

MIT


Overview (`packages/pug-parser/README.md`)

pug-parser

The pug parser (takes an array of tokens and converts it to an abstract syntax tree)




Installation

text
npm install pug-parser

Usage

js
var parse = require('pug-parser');

`parse(tokens, options)`

Convert Pug tokens to an abstract syntax tree (AST).

options can contain the following properties:

  • filename (string): The name of the Pug file; it is included in the produced AST nodes and error handling, if provided.
  • plugins (array): An array of plugins, in the order they should be applied.
  • src (string): The source of the Pug file; it is used in error handling if provided.
js
var lex = require('pug-lexer');

var filename = 'my-file.pug';
var src = 'div(data-foo="bar")';
var tokens = lex(src, {filename});

var ast = parse(tokens, {filename, src});

console.log(JSON.stringify(ast, null, '  '))
json
{
  "type": "Block",
  "nodes": [
    {
      "type": "Tag",
      "name": "div",
      "selfClosing": false,
      "block": {
        "type": "Block",
        "nodes": [],
        "line": 1,
        "filename": "my-file.pug"
      },
      "attrs": [
        {
          "name": "data-foo",
          "val": "\"bar\"",
          "line": 1,
          "column": 5,
          "filename": "my-file.pug",
          "mustEscape": true
        }
      ],
      "attributeBlocks": [],
      "isInline": false,
      "line": 1,
      "column": 1,
      "filename": "my-file.pug"
    }
  ],
  "line": 0,
  "filename": "my-file.pug"
}

`new parse.Parser(tokens, options)`

Constructor for a Parser class. This is not meant to be used directly unless you know what you are doing.

options may contain the following properties:

  • filename (string): The name of the Pug file; it is included in the produced AST nodes and error handling, if provided.
  • plugins (array): An array of plugins, in the order they should be applied.
  • src (string): The source of the Pug file; it is used in error handling if provided.

License

MIT


Overview (`packages/pug-runtime/README.md`)

pug-runtime

The runtime components for the pug templating language




Installation

text
npm install pug-runtime

Usage

You can call runtime methods directly using runtime.method. This is particularly useful when compiling to deal with things that are already known at compile time.

js
var runtime = require('pug-runtime');

assert(runtime.attr('foo', 'bar', true, true) === ' foo="bar"');

You can also build a string with a given list of functions available as pug_method by calling build(arrayOfMethods). This is useful for inlining runtime functions within the compiled templates.

js
var build = require('pug-runtime/build');
var src = build(['attr']);

var attr = Function('', src + ';return pug_attr;')();
assert(attr('foo', 'bar', true, true) === ' foo="bar"');

When testing code compiled for the browser in Node.js, it is necessary to make the runtime available. To do so, one can use require('pug-runtime/wrap'):

js
var pug = require('pug');
var wrap = require('pug-runtime/wrap');

var pugSrc = 'p= content';
// By default compileClient automatically embeds the needed runtime functions,
// rendering this module useless.
var compiledCode = pug.compileClient(pugSrc, {
  externalRuntime: true
});
//=> 'function template (locals) { ... pug.escape() ... }'

var templateFunc = wrap(compiledCode);
templateFunc({content: 'Hey!'});
//=> '<p>Hey!</p>'

// Change template function name to 'heyTemplate'
compiledCode = pug.compileClient(pugSrc, {
  externalRuntime: true,
  name: 'heyTemplate'
});
//=> 'function heyTemplate (locals) { ... }'

templateFunc = wrap(compiledCode, 'heyTemplate');
templateFunc({content: 'Hey!'});
//=> '<p>Hey!</p>'

License

MIT


Overview (`packages/pug-strip-comments/README.md`)

pug-strip-comments

Strips comments from Pug token stream




Installation

text
npm install pug-strip-comments

Usage

js
var lex = require('pug-lexer');
var stripComments = require('pug-strip-comments');

var tokens = lex('//- unbuffered\n// buffered');
// [ { type: 'comment', line: 1, val: ' unbuffered', buffer: false },
//   { type: 'newline', line: 2 },
//   { type: 'comment', line: 2, val: ' buffered', buffer: true },
//   { type: 'eos', line: 2 } ]

// Only strip unbuffered comments (default)
stripComments(tokens, { filename: 'pug' });
// [ { type: 'newline', line: 2 },
//   { type: 'comment', line: 2, val: ' buffered', buffer: true },
//   { type: 'eos', line: 2 } ]

// Only strip buffered comments (when you want to play a joke on your coworkers)
stripComments(tokens, { filename: 'pug', stripUnbuffered: false, stripBuffered: true });
// [ { type: 'comment', line: 1, val: ' unbuffered', buffer: false },
//   { type: 'newline', line: 2 },
//   { type: 'eos', line: 2 } ]

// Strip both (if you want Pug VERY clean)
stripComments(tokens, { filename: 'pug', stripBuffered: true });
// [ { type: 'newline', line: 2 },
//   { type: 'eos', line: 2 } ]

License

MIT


Overview (`packages/pug-walk/README.md`)

pug-walk

Walk and transform a Pug AST





Installation

text
npm install pug-walk

Usage

js
var walk = require('pug-walk');

`walk(ast, before, after, options)`

Traverse and optionally transform a Pug AST.

ast is not cloned, so any changes done to it will be done directly on the AST provided.

before and after are functions with the signature (node, replace). before is called when a node is first seen, while after is called after the children of the node (if any) have already been traversed.

The replace parameter is a function that can be used to replace the node in the AST. It takes either an object or an array as its only parameter. If an object is specified, the current node is replaced by the parameter in the AST. If an array is specified and the ancestor of the current node allows such an operation, the node is replaced by all of the nodes in the specified array. This way, you can remove and add new nodes adjacent to the current node. Whether the parent node allows array operation is indicated by the property replace.arrayAllowed, which is set to true when the parent is a Block and when the parent is a Include and the node is an IncludeFilter.

If before returns false, the children of this node will not be traversed and left unchanged (unless replace has been called). Otherwise, the returned value of before is ignored. The returned value of after is always ignored. If replace() is called in before() with an array, and before() does not return false, the nodes in the array are still descended.

options can contain the following properties:

  • includeDependencies (boolean): Walk the AST of a loaded dependent file (i.e., includes and extends). Defaults to false.
  • parents (array): Nodes that are ancestors to the current ast. This option is used mainly internally, and users usually do not have to specify it. Defaults to [].
text
/* Detailed source-code truncated for AI context efficiency. */

License

MIT


Overview (`packages/pug/README.md`)

Pug

Full documentation is at pugjs.org

Pug is a high performance template engine heavily influenced by Haml
and implemented with JavaScript for Node.js and browsers. For bug reports,
feature requests and questions, open an issue.
For discussion join the chat room.

You can test drive Pug online here.






Rename from "Jade"

This project was formerly known as "Jade." However, it has been revealed to us that "Jade" is a registered trademark, and as a result a rename is needed. After some discussion among the maintainers, "Pug" has been chosen as the new name for this project. The next major version will carry "pug" as the package name.

If your package or app currently uses jade, don't worry: we have secured permissions to continue to occupy that package name, although all new versions will be released under pug.

Before the renaming, we had already begun working on an incompatible Jade 2.0.0. We have then made it so that this new major version bump will coincide with the rename to Pug. Therefore, upgrading from Jade to Pug will be the same process as upgrading any other package with a major version bump. Currently, Pug 2.0.0 is still under beta stage, and there are several syntactic differences we have deprecated and removed. Such differences are documented at #2305.

The website and documentation for Pug are still being updated, but if you are new to Pug, you should get started with the new syntax and install the Pug package on npm.

Installation

Package

via npm:

bash
$ npm install pug

Command Line

After installing the latest version of Node.js, install with:

bash
$ npm install pug-cli -g

and run with

bash
$ pug --help

Syntax

Pug is a clean, whitespace sensitive syntax for writing html. Here is a simple example:

pug
doctype html
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) bar(1 + 5)
  body
    h1 Pug - node template engine
    #container.col
      if youAreUsingPug
        p You are amazing
      else
        p Get on it!
      p.
        Pug is a terse and simple templating language with a
        strong focus on performance and powerful features.

becomes

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pug</title>
    <script type="text/javascript">
      if (foo) bar(1 + 5)
    </script>
  </head>
  <body>
    <h1>Pug - node template engine</h1>
    <div id="container" class="col">
      <p>You are amazing</p>
      <p>Pug is a terse and simple templating language with a strong focus on performance and powerful features.</p>
    </div>
  </body>
</html>

API

For full API, see pugjs.org/api/reference.html

js
var pug = require('pug');

// compile
var fn = pug.compile('string of pug', options);
var html = fn(locals);

// render
var html = pug.render('string of pug', merge(options, locals));

// renderFile
var html = pug.renderFile('filename.pug', merge(options, locals));

Options

  • filename Used in exceptions, and required when using includes
  • compileDebug When false no debug instrumentation is compiled
  • pretty Add pretty-indentation whitespace to output (false by default)

Browser Support

The latest version of pug can be download for the browser in standalone form from here. It only supports the very latest browsers though, and is a large file. It is recommended that you pre-compile your pug templates to JavaScript.

To compile a template for use on the client using the command line, do:

bash
$ pug --client --no-debug filename.pug

which will produce filename.js containing the compiled template.

Additional Resources

Tutorials:

Implementations in other languages:

Other:

License

MIT


Overview (`packages/pug/examples/README.md`)

The examples in this directory can be run simply by something like.

text
node attributes.js

You can also open browser.html in a browser.


Overview (`packages/pug/test/README.md`)

Running Tests

To run tests (with node.js installed) you must complete 2 steps.

1 Install dependencies

text
npm install

2 Run tests

text
npm test

Overview (`packages/pug/test/anti-cases/readme.md`)

This folder collects examples of files that are not valid pug, but were at some point accepted by the parser without throwing an error. The tests ensure that all these cases now throw some form of error message (hopefully a helpful one).


--- METRICS ---