Learn Pug Template Engine from Scratch in One Video

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started

A Template Engine is so necessary when it comes to delivering complex user interfaces and having full control over your HTML pages which nowadays it is supported with most of the frameworks you work with, Pug is one of the best Template Engine when it comes to simplicity and features and how easy it is to get started with for anyone who has a basic knowledge about basic HTML Web page structure.

Pug was named Jade before it changes its name to Pug template engine it is mostly supported by any framework or language you decided to develop your backend (server-side) with, and for its simple design and structure that's why you should consider using it over other available engines.

If you want to follow along with the tutorial you can get the bare repository which has a simple Node.js Express Server with Pug from Github, otherwise, you can use your own project.

First, you need to install pug I have a Node.js Express server project so I use NPM but depending on the framework you are using and technology you can get Pug and install it.

npm install pug --save

You can check the Official Pug website for frameworks support info.

Pug Template Structure and Tags

You will notice that it makes HTML Pages creation much easier and simple and never complain about how the code is badly structured or why you can understand how things are actually connected.

Now go under your public folder or where ever you put your static served website asset (for me it is /dist) and create a new file name it index.pug.

/* index.pug */
html 
  head
    title Hello World
  body 
    h3 Welcome to Pug Template Engine

The above code is a regular HTML Page but written in Pug template specific syntax.

As you can see that there are no tags when creating an element and the most important thing is when you open a tag you don't have to close it, here is what you should consider:

  • For creating tags you just need to specify the name of the tag without opening or closing brackets.
  • You only need to open the tag but no need to close it.
  • For putting an element as a child of another element you only need to indent the child inside the parent (child indentation or margin from the left side more than the parent's spacing)
  • Putting text inside a tag you simply put it alongside the tag name just leave a space (for now we only have text content).
  • And of course, the extension of the template should be .pug.

Now, you need to render or use the pug core template engine to convert it's template into regular HTML document for the browser to be able to read it, again I'm using Express and pug integrates so seamlessly with Express all you have to do is return response and tell it to render pug template.

For rendering Pug on Express, first, make sure to tell to use pug as a view engine (template engine).

//Use a Custom Templating Engine
app.set("view engine", "pug");

Then you need to change the default views directory of where express will look for your templates, by default express will look at views directory on the root folder.

//Change Views Default Directory (my public folder is dist)
app.set("views", path.resolve("./dist"));

For rendering the template (compiling the template into regular HTML) when a root is requested you can use the render method on the response.

//When user access the main page 
router.get("/", (req, res, next) => {
   //Render then send HTML Page back to user 
   res.render("index"); ///< render pug template 
});

You can try to run the Express Server and go to http://localhost:3000 or where ever you main server page is to see if it actually works.

Pug Attributes and Interpolation

Well, the most needed thing to learn about template engine specific logic and syntax after getting how elements work and how to put content inside of them, now, we need to know to add attributes on element either standard attributes or custom ones.

  body 
    p(id="paragraph", class="p-red", data-custom="checked") this is a paragraph...

Here, we create a new paragraph but as you can notice that we used the (p) tag as a function (if you familiar on function) we open parenthesis to set the attributes of the current element, in this case, we set the id to paragraph and two more properties, we even set the value of a custom attribute (data-custom).

For Attributes you first specify the name of the attribute (either standard or custom) then you set it equals to a value in this case we set it to a constant string value, of course, you need to specify that on a double quotation ("constant text").

Each Attribute is separated with a comma from the others.

You can also put only Attribute name without the value so it would be treated as to use the value the same as its name and boolean attributes which are treated as a string if the value is true otherwise, if false the attribute is completely discarded.

p(id="paragraph", something=true, nothing=false, checked) this is another paragraph...

When rendered you will get:

<p id="paragraph" something="something" checked="checked"></p>

You can also set a style attributes of an element.

p(style={color: "magenta", background: "url(img.png)"})
//You would get the same result as 
<p style="color: magenta; background: url(img.png)"></p>

Now, what is an interpolation?

Interpolation allows you to create custom variables on your template and use them across different elements and expressions as well how to use escaped and unescaped text.

- var myID = "main-container"
div(id=myID) this is a container

For creating variables we have first to tell the template engine that this is a variable and not a tag element by prepending a dash (-) at the beginning of the line where we define our variable, then we use var keyword and its name comes afterward.

The result will be:

<!-- Variables will not show up here -->
<div id="main-container">this is a container</div>

You can also include variable content into elements or text.

- var name = "alex"
p The Member Name is: #{name}

To include a variable value into a string you have to put it between curly braces which starts with a hashtag.

Or even include a tag inside the text.

- var name = "alex"
p The Member Name is: #{name} #[strong this is Bold]

And it will be the same as putting nested elements.

<p>The Member Name is: alex <strong>this is bold</strong></p>

For unescaped character use (!) instead of a hashtag (#) at the beginning of the curly braces.

- var bold = <strong>The Moon</strong>
div i'm at !{bold}
//Converted to:
<div>i'm at <strong>The Moon</strong></div>

Dynamic Data Passing

As long as you could create and use your own variables on tags and it's content we can pass variables from javascript file or simply from the outside of the template into the template, this can be used for many cases and scenarios, for example you may need to show the current Route URL on the template so you have got to pass it from your application.

h3 my name is #{username}

In the above template, we used the username variable but is it declared on the template score so we expecting it to be passed on render.

//On template render you can pass an object of data to be included in the current template
res.render("index", { username: "Alexrc" });

Conditional Statements & Cases

You also have the ability to use if else statements on your template for conditional rendering.

- var checked = true
- var agent = { job: "web dev" }
div 
  if agent.job 
    h4 agent.job
  else if checked
    p Valid User
  else 
    span#red rejected

For if else statements it is simply a regular javascript and when a condition is met you render something upon that.

We check if the agent object has a job property and it's not null then we render it otherwise we check the boolean variable.

(span#red) is like referencing a span element with red id on CSS but on Pug, it's a shortcut for creating a span with a red id just to make things a bit shorter.

If you have a lot of if statements you can replace them with a switch case but in Pug it's called a Case.

var choice = 0
case choice
  when 1
    p Welcome to The Game 
  when 2
    span.intent running script...
  default
    span.error cannot process this choice!

Cases can be helpful in some cases two instead of using a lot of if else statements, you may also use a break statement on a choice that does nothing for example so the case will exit and you code execution will carry on normally.

Loops & Comments

Iterating over a list or object properties is super important when it comes to dealing with a database data fetching in and rendering it using your template in that case you can use Pug loops (while or for) to get each instance of a list and render it properly.

 Let's say you have a list of trending frameworks and you want to render them each one in a list item.

- var frameworks = ["React", "Angular", "Vuejs"]
ul
  each item in frameworks
    li #{item}

instead of regular for loop on javascript you use the each...in syntax to iterate through a list of items whatever the items are (strings, numbers, object) you can use it normally as you would deal with a javascript iteration but with a bit different syntax.

After running the above template on the engine you should get:

<ul>
  <li>React</li>
  <li>Angular</li>
  <li>Vuejs</li>
</ul>

Whatever expression you need to use it is possible on the iteration (loop) scope.

 You can also retrieve the index of the item as you would in a normal for loop.

ul
  each item, index in [1, 4, 8, 10, 12]
    li index as #{item}

Or use Traditional while loops with a hardcoded index.

- i = 0
div 
  while i < 3
    span iteration index #{i++}

The ( i ) index will put the value and evaluate at the same time so the loop can carry on, so simply imagine it as you are working with a language like javascript but rendering HTML elements.

Check the official Docs for more examples and use cases.

Including Scripts and Templates

As your application gets bigger you should consider refactoring your code base from single template file into multiple tiny templates each one has its role for a specific section of the webpage either a route or simply for splitting the webpage sections (Header, Content, Footer...), therefore Pug supports including other templates into your current template.

Let's try to move the header section on our template into a separate small template file then include it on the main template.

/* head.pug */
head
  title Pug Site
  //You can also include scripts (local or from a CDN)
  script(src="http://cdn.example.com/script.js")

Then simply include in the app template.

/* index.pug */
html
  //Include other template with file path without quotiatr
  include ./includes/head.pug
 
  body
  ...

When the tamplate compiles into plain HTML you get the same as you would put all the templates code in one single template file.

<html>
  <head>
    <title>Pug Site</title>
    <script src="http://cdn.example/com/script.js"></script>
  </head>
  <body>
   <!-- Your Body Content Here -->
  </body>
</html>

So any tag you use regularly on HTML you can normally use it on Pug with its standard parameters so you can imagine your self-working with a normal HTML page but using simpler syntax and add features for building your next big project.

Pug Mixins (Functions) 

Mixins are so usefull when it comes to using a certain block of code over and over on your code base so you can define a mixin for this specific section with a custom argument(s) and call it (like a function) whenever is needed.

//Mixin Declaration
mixin frameworksList(list)
  ul 
    each item in list
      li= item

//You did only declare the mixin but still need to call it in order for it to execute and output
div
  +frameworksList(["React", "Angular", "Vuejs"])

First, you need to declare the mixin, take it as a function so you have to give it a body the arguments are options, in this example, we expect a list of frameworks to be rendered on an unordered list then we simply loop over the list items and render each one of them.

For calling a mixin you need to use the plus sign (+) alongside the declared mixin name and parentheses only if you gave it arguments otherwise, you can discard it.

Mixins are generally used for having redundant free-code, instead of copy pasting a section of your webpage and having rubbish code all over your template you use makes it simplify your life as a Web Developer.

 

What's Next

After going through this tutorial carefully either watching the video tutorial or reading through the lines you should be able now to know everything you need to start with Pug and create your templates since it is very simple and has a very nice and clean Documentation make sure to read it for more explained info.

 

 

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games