Introduction
Pug replaces verbose HTML angle brackets with a whitespace-sensitive syntax inspired by Haml. It compiles templates into high-performance JavaScript functions that output HTML strings, and supports mixins, includes, inheritance, and conditionals out of the box.
What Pug Does
- Compiles indentation-based templates into HTML with no closing tags needed
- Supports template inheritance with
extendsandblockfor layout reuse - Provides mixins for reusable template components
- Includes conditionals, loops, and interpolation within templates
- Integrates with Express.js as a view engine with zero additional setup
Architecture Overview
Pug processes templates in three stages: lexing (tokenizing the indented source), parsing (building an AST from tokens), and code generation (compiling the AST into a JavaScript render function). The compiled function accepts a data object and returns an HTML string. Templates can be pre-compiled at build time for production performance, avoiding runtime parsing overhead.
Self-Hosting & Configuration
- Install via npm:
npm install pugfor the API ornpm install -g pug-clifor the CLI - Use as an Express view engine:
app.set('view engine', 'pug') - Place template files with
.pugextension in your views directory - Enable pretty-printing with
{ pretty: true }during development - Pre-compile templates with
pug.compileFile()for production use
Key Features
- Concise syntax eliminates closing tags, angle brackets, and most quotation marks
- Template inheritance lets you define base layouts and override specific blocks
- Mixins act as reusable functions that accept arguments and produce markup
- Filters allow embedding Markdown, CoffeeScript, or other formats inline
- Supports both buffered and unbuffered JavaScript code within templates
Comparison with Similar Tools
- EJS — uses standard HTML with embedded JS tags; Pug uses its own indented syntax
- Handlebars — logic-less templates with helpers; Pug allows full JavaScript expressions
- Nunjucks — Jinja2-inspired syntax closer to HTML; Pug is more concise but less familiar
- JSX — used in React for component-based UIs; Pug targets server-side HTML rendering
FAQ
Q: Is Pug the same as Jade? A: Yes. The project was renamed from Jade to Pug in 2016 due to a trademark issue. The syntax and functionality are the same.
Q: Can I use Pug with frameworks other than Express? A: Yes. Pug compiles to plain JavaScript functions, so it works with Koa, Fastify, or any environment that can call a render function.
Q: Does Pug support HTML5 doctype?
A: Yes. Use doctype html at the top of your template to output <!DOCTYPE html>.
Q: Is Pug suitable for large projects? A: Yes. Template inheritance, mixins, and includes help organize large template codebases effectively.