Getting started with Pug template engine

Clean and organize HTML, that’s what we as Front-end Developers always aim for. Well with Pug, formerly known as “Jade” (a registered trademark, and as a result a rename was needed) it’s a high performance and feature-rich templating engine that’s easy to achieve. Simply put, Pug is a clean, white space/indentation sensitive syntax for writing html.

Just like SASS, Pug is a prepocessor and, as such it helps you accomplishing tasks like wrapping away repetitive work by providing features not available in plain HTML. 
It provides the ability to write dynamic and reusable HTML documents, its an open source HTML templating language for Node.js (server-side JavaScript), totally free to use and provides fast, easy, and fun HTML.

When using modern CSS frameworks like Bootstrap and Foundation, most of the development becomes entirely about producing HTML, which brings out the power of Pug. Once you start using it, it’ll become an indispensable tool for you.

So, let’s get it on with it!

Just like the programming language Python, Pug works with indentation or white spaces, like this example:

doctype html  
html(lang='en')
head
title Pug
body
h1 Pug Examples
div.container
p Cool Pug example!

As you can see it’s much cleaner and easy to read than an ordinary HTML document, there are no closing tags, Pug is handling this, everything is indented and you scan the file much quicker. Also by using Pug we can ensure that our HTML is well-formed and valid.

This will translate to:

<!DOCTYPE html>  
<html lang="en">
<head>
<title>Pug</title>
</head>
<body>
<h1>Pug Examples</h1>
<div class="container">
<p>Cool Pug example!</p>
</div>
</body>
</html>

During the time Pug is compiling the .pug file to plain HTML, the compiler throws build errors if the indention in your file isn’t correct. 
As such it also acts as an error prevention tool for making mistakes in the Front-end.

Ok, you got my attention, so how do we start using it?


Installing Pug

Like most tools nowadays, Pug is a node package that can easily be installed on your system using the following npm command:

$ npm install pug –g

Note: You need to have installed NodeJS in order to run npm commands from the terminal. In this article I’ll show you the core features of Pug, to start let’s create our first file. 
As I mentioned earlier, Pug files use the .pug extension, you don’t need to type the angle brackets and because of the indentation you can also ignore the closing tags.

html  
head
title This is my first Pug file
body
header
p My soon to be menu
section
p This is a post about Pug template engine, enjoy it!
footer
cool footer with lots of copyrights

Now that we have our index.pug template In order to compile it to HTML we need to open the terminal and navigate to the folder containing our file and run the command:

$ pug index.pug

This simple command will create the corresponding HTML file next to the Pug one. 
As you may been noticing, the text can be written in our html tags in three ways, first putting the indented text below the tag with a pipe | before it.

p  
| My text inside the p tag

The second way by placing a dot in the html tag and indenting the text below (with no |).

p.  
Lorem ipsum dot sit…

The third one and one of the most common is simply writing the text after the HTML tag.

p Yes this works too.

Ok, so we have now our HTML code written in a very neat way, easy to understand but let’s extend it and start adding our normal classes and data attributes. 
To do this let’s use a link tag for example:

a.foo_link(href='about.html', target='_blank') About Us

which will generate: About Us

Simple right? inside the parenthesis you can add all the attributes you need even the .foo_linkclass, or an ID. If instead you were creating the most common HTML element, a <div> you could write it in these many ways:

.container
.container.left
div.container.left
#container.left
div#container.left

Since we can already write normal HTML and specify attributes to it, let’s add a stylesheet and import a javascript file for example. 
To do this, just like normal html tags, you pass the script and style attributes in the same way:

link(href='/css/styles.css', rel='stylesheet')
script(type='text/javascript').  
var myVar = ‘Hello Var’;
console.log(myVar);
script(src='/javascripts/app.js')

Like adding attributes to html you pass parameters to the parenthesis and call the file you want to import.

Pretty cool syntax so far!

Now onto the feature rich part of Pug, this awesome feature allows you to create reusable blocks of html very fast. In order to keep your project structure clean, you should place your mixins in separated files and only load them if they are required.

The basic syntax to define a mixin is as follows:

//- Declaration (invoice-mixin.pug)
mixin invoice
.invoice-wrapper
h2 Invoice
ul
li number
li email

Then, wherever we need this mixin, we just use it in another template file as follows:

section  
+invoice <--- Just like this!
p This is a post about pug template engine, enjoy it!

As you may notice, this is not a very useful mixin, but as you create more powerful ones, when you start introducing conditionals, looping etc, they really become a must use feature to keep your code organised.

mixin header_block(title, link)  
header
h3.main-title #{title}
ul
li
a(href='#{link}', target="_blank")
+header_block('Amazing title here!', 'features.html')

This will render the Amazing title here in #{title} placeholder and the features.html in the #{link}.

Just like mixins, Pug provides us with another similar feature called Blocks. A block is a piece of Pug code that can be placed within a child template as many times and as many different blocks you need.

// home-template.pug
extends layout.pug
block head  
script(src="/javascripts/jquery.js.js")

block content  
h1 My home page

and in the other file:

doctype 5  
html
head
title My title
block head <!-- will render the script call -->
body
#content
block content <!-- will render the h1 -->
Block append & prepend
The block feature can be extended even further by using the prepend or append blocks. Suppose for example you have default scripts in a "scripts" block that you wish to use on every page:
// container-scripts.pug
.container
block scripts
script(src='/javascripts/bootstrap.js')
script(src='/javascripts/app.js')

Now in the other pug file:

//main-layout.pug
extends footer.pug
append scripts  
script(src='/javascripts/jquery.js')

This will add the two scripts from footer.pug to the new file, by appending them after the bootstrap.js call out.

Notice the append scripts, if we don’t use the append when the block renders to the main-layout.pug it will overwrite the already present script declaration, so this way we are appending the script declaration to the one that already exists in the file.

Resulting in:

<script src="/javascripts/bootstrap.js"></script>
<script src="/javascripts/jquery.js"></script>
<script src="/javascripts/app.js"></script>
</body>
</html>

Inheritance in Pug

You have noticed in the previous templates examples the extends declaration, Pug allows you to inherit HTML structures by offering the extends command which can be used to achieve a modular approach to build web views, just like having a master view and a whole bunch of sub views that extend the master one.

// file master-view.pug
html
head
title My Blog
link(rel='stylesheet', href='/styles/bootstrap.min.css)
body
.container
block content
script(src='/scripts/angular.min.js')

And in other view file:

extends master-view.pug
block content  
.row
.col-md-3
nav
.col-md-9
h1 welcome

We could wrap up this pug introduction already but it wouldn’t touch one of the most useful features, in my opinion, that Pug has. 
Conditionals are needed everywhere, even in our views to quick add some simple logic. This is where Pug excels by allowing to create simples pieces of logic like if/else statements that save you a lot of time and lines! Again there is no need for parentheses or braces.

- var language = "Pug"
if language == "Pug"  
p Awesome
else
p Not awesome

renders: <p>Awesome</p> Yes, that simple!

So far you’ve been introduced to a full Pug specification, you are now able to create html files in Pug language, structure your views a lot better, be more organised, but let’s go further and integrate Pug with your favourite build system, Gulp. After all you don’t want to always have to go back to the terminal and compile the Pug files, you want this process to be automatic. 
The reasons to use template engines are entirely up to you, but in my opinion they can help you achieve more productivity, less repetition, and writting a more pleasant syntax. This is where a language like Pug, that helps to keep your code concise and simple, comes into play.

If you’re interested in integrate the Pug template engine with a build system like Gulp, to automatically build your Pug files to HTML, please feel free to continue reading.


Pug with Gulp system:

This will be a pain free, quick and easy setup to bundle Pug with Gulp build system, the steps:

  • Installing Gulp
  • Creating a basic folder structure for our pug templates
  • Creating a package.json so that node knows what to instal (pug & gulp-pug)
  • Create the gulp task to compile our pug to html

Installing Gulp There’s a NPM command for that. To install it, all we need to do is run:

npm install --save gulp-install

File structure With Gulp installed, let’s setup the directory where our project will be placed, simply create a containing folder inside a templates/ folder for all the pug files, and in the main folder root add a package.json file.

This file will include:

{
"devDependencies": {
"gulp": "^3.9.0",
"gulp-pug": "^3.0.0:
}
}

Now run npm install so that node adds the gulp-pug dependency needed for it to compile, to our node_modules folder.

Create the file gulpfile.js, it can be in the folder root. This is where we are going to assign the command that gulp will use to understand our pug file in the templates folder and compile it to a new build folder.

Open the gulpfile.js and write the following task:

var gulp = require('gulp'),  
pug = require('gulp-pug');

// run this task by typing in gulp pug in CLI
gulp.task('pug', function() {
return gulp.src(templates/*.pug')
.pipe(pug()) // pipe to pug plugin
.pipe(gulp.dest('build)); // tell gulp our output folder
});

After this, with our gulpfile.js set up, all we need to do is run the command gulp pug in our root project directory and let the magic happen! You will see a folder named “build” appear. If you explore this build folder you will see our html file. However for Gulp to automatically run the task jus run gulp serve and it will be watching for changes as you hit save during your work in the Pug file and updates the html file in the build folder. Easy peasy! Now you have nice workflow with the Pug template engine! 
Why use Pug?

Still asking why? As you can see using a template engine instead of your standard HTML is a great way to introduce organisation and consistency to our code. By doing so, Pug helps you write cleaner code, which makes it less tedious to do your job. 
It even works with other languages like Python, Ruby, Node, take a look at the ExpressJS example, it’s so dead simple to use it.

As a result the organisation using pug blocks and cleanness gained from a template engine, like Pug, speeds up debugging, allows you to develop faster using mixins, with little chance for errors, and provides a good separation between logic and markup. It’s the perfect combination to use with a client side framework like Angular for example. What’s not to like? Give it a try, it’s that good.

There is more you can learn about Pug that we didn’t cover in this tutorial, so you can check out the official documentation for more.

Blog article: http://www.hostilejourney.com/getting-started-with-pug-template-engine/

Some nice resources:

HTML to Pug: http://html2jade.org/ 
NPM Gulp package: https://www.npmjs.com/package/gulp-pug 
NPM Pug package: https://www.npmjs.com/package/pug 
Gihub Source: https://github.com/pugjs/pug