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:

title this is a website built with pug!
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>
<title>this is a website built with pug!</title>
<meta charset="utf-8">
<h1>Look Mom, no curly braces! :D</h1>
<div class="container">woah, so div</div>

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