Getting Started with Pug JS

Functional programming is so popular, in part, because it abstracts away logic into smaller, re-usable components. This also means that, as developers, we get to type less code. This is great for the lazier among us, myself included, but without using HTML or CSS pre-processors, the functional paradigm only extends to our JavaScript files. My aim here is for you to leave this article ready to start writing shorter, more powerful markup.

Pug is a powerful templating engine that allows us to write highly readable, terse, and elegant markup. Although it is generally used for Node.js environments, it also works with the browser.

Enough talk, though, let’s get to the code!

Here is the start of a very simple webpage built with Pug:

doctype
html
head
title this is a website built with pug!
meta(charset="utf-8")
body
h1 Look Mom, no curly braces! :D
div(class="container") woah, so div

Here is the same pug code compiled to plain old HTML:

<!DOCTYPE html>
<html>
<head>
<title>this is a website built with pug!</title>
<meta charset="utf-8">
</head>
<body>
<h1>Look Mom, no curly braces! :D</h1>
<div class="container">woah, so div</div>
</body>
</html>

The first thing you might notice is the lack of the traditional HTML carrot tags. Not only that, but closing tags are mysteriously absent as well. This is because Pug respects white-space. The first set of characters on line will be compiled to the name of the tag. Anything on that line but after the first space will be interpreted as the body of the tag. Nesting children within parent components is achieved by indentation: The title and meta tags are children of the head tag because they are indented one tab from the position of the head tag.

Beautiful, right? In this example, the pug code requires roughly 25% less characters than traditional HTML. :D

This could be even better, though. In my experience, the majority of structural components in markup are DIVs. Fortunately, pug offers an even shorter short-hand for writing divs.

.ThisIsHowYouWriteAClass  SO DIV
#ThisIsHowYouWriteAID TOO MANY DIVS ON THE DANCE FLOOR