Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

What is Pug

A template engine is a program that builds HTML from a template and data. The template describes the markup once, and the engine fills in headings, lists and links and produces finished HTML files. Pug is a popular template engine for Node.js with a short syntax: instead of angle brackets and closing tags it uses indentation.

This course uses Pug 3, the current version of the pug package. The package used to be called Jade; in older articles you will see that name and .jade files.

From Pug to HTML

Here is a small navigation menu in the file src/index.pug:

nav
  a(href="index.html") Home
  a(href="menu.html") Menu
  a(href="contacts.html") Contacts

The tag name starts the line, attributes go in parentheses, text follows after a space. Nesting is set by indentation: the links are shifted to the right, so they are inside nav. Pug turns this file into ordinary HTML:

<nav><a href="index.html">Home</a><a href="menu.html">Menu</a><a href="contacts.html">Contacts</a></nav>

Pug added the closing tags itself. The browser receives only this HTML; the .pug file stays with you.

What Pug gives you

FeatureWhy it helps
Short syntaxLess typing, you cannot forget to close a tag
VariablesThe site name or a price is written once
Conditionals and loopsA list built from data instead of twenty copied lines
MixinsA repeated piece of markup, such as a card, with parameters
IncludesHeader and footer in separate files shared by all pages
Template inheritanceOne shared page layout; other pages only fill it in

Where Pug runs

Pug runs in Node.js, not in the browser. There are two ways to use it:

  • at build time — a script turns .pug files into .html, and you upload the finished pages to any hosting;
  • on a server — a server, for example one built with Express, renders the page again on every request with fresh data.

Most of the course uses the first way; one of the last lessons covers the second.

The course example

Throughout the course you build a small site for the Morning Café with three pages: home, menu and contacts. All pages share a layout, a header with navigation and a footer, and the menu is built from a list of drinks with prices.

Common mistake

The browser does not understand Pug. If you put Pug code into an .html file or link a .pug file, the browser shows it as plain text:

nav
  a(href="index.html") Home

First turn the template into HTML, and open the result in the browser. The next lesson shows how.

Thanks for reading!

Donate to the site — we work hard for you.