We now have a youtube channel. Subscribe!

Express.js | Templating

Express.js | Templating


Hello folks! Welcome back to a new edition of our tutorial on ExpressJS. In this tutorial guide, we are going to be discussing about ExpressJS Templating.

Pug (formally known as Jade) is a template engine for Express. Templating engines are used to remove the clustering of our server code with HTML, and concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features which includes filters, includes, inheritance, interpolation, etc.

To use pug with Express, we need to install it,

npm install --save pug

Now that Pug is successfully installed, set it as the templating engine for your app. You do not need to 'require' it. Add the following line of code to your index.js file.

app.set('view engine', 'pug');
app.set('views','./views');

Now create a new directory known as views. Inside that create a file called first_view.pug, and enter the following data in it.

doctype html
html
   head
      title = "Hello Pug"
   body
      p.greetings#people Hello World!

To run this page, add the following route to your app -

app.get('/first_template', function(req, res){
   res.render('first_view');
});

You will get the output as - Hello World! Pug converts this very simple looking markup to html. We don't need to keep track of closing our tags, no need to make use of class and id keywords, rather utilize '.' and '#' to define them. The above code first get converted to -

<!DOCTYPE html>
<html>
   <head>
      <title>Hello Pug</title>
   </head>
   
   <body>
      <p class = "greetings" id = "people">Hello World!</p>
   </body>
</html>

Pug is able to do a lot more than simplifying HTML markup.


Vital Features of Pug

Let's now explore a few important features of Pug.

Simple Tags

Tags are nested based on their indentation. Like in the above code, <title> was indented within the <head> tag, so it was in it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag.

We don't need to close tags, as soon as Pug comes across the next tag on same or outer indentation level, it closes the tag for us.

To put text inside a tag, we have 3 methods -

  • Space separated
h1 Welcome to Pug
  • Piped text
div
   | To insert multiline text, 
   | You can use the pipe operator.
  • Block of text
div.
   But that gets tedious if you have a lot of text.
   You can use "." at the end of tag to denote block of text.
   To put tags inside this block, simply enter tag in a new line and 
   indent it accordingly.

Comments

Pug uses the same syntax as JavaScript(//) to create comments. These comments are converted to html comments(<--comment-->). For example,

//This is a Pug comment

The above comment gets converted to the following -

<!--This is a Pug comment-->

Attributes

To define attributes, make use of a comma separated list of attributes. The class and ID attributes have special representations. The following line of code covers the defining attributes, classes and id for a specific html tag.

div.container.column.main#division(width = "100", height = "100")

The above line of code get converted to the following -

<div class = "container column main" id = "division" width = "100" height = "100"></div>


Parsing Values to Templates

Whenever we render a Pug template, we can pass it a value from our route handler, which we can then use in our template.

Example

Create a new route handler making use of the following.

var express = require('express');
var app = express();

app.get('/dynamic_view', function(req, res){
   res.render('dynamic', {
      name: "WebDesignTutorialz", 
      url:"http://www.webdesigntutorialz.com"
   });
});

app.listen(3000);

And create a new file in views directory, and name it dynamic.pug, utilizing the following code -

html
   head
      title=name
   body
      h1=name
      a(href = url) URL

Output

Go to localhost:3000/dynamic_view in your web browser; you should get the following output -

templating_variables

We can also use these passed variables in between text. To insert passed variables in between text of a tag, use #{variableName} syntax.

Example

In the above example, if we wanted to insert Greetings from WebDesignTutorialz, then we could have done the following -

html
   head
      title = name
   body
      h1 Greetings from #{name}
      a(href = url) URL

Output

This method of utilizing values is known as interpolation. The above code will display the following output -

templating_interpolation

Conditionals

We can make use of conditional statements and looping constructs also.

Example

Consider the following -

If a User is logged in, the page should show "Hi, User" and if not, then the "Login/Signup" link. To achieve this, we can define a simple template like -

html
   head
      title Simple template
   body
      if(user)
         h1 Hi, #{user.name}
      else
         a(href = "/sign_up") Sign Up

When we render this utilizing our routes, we can pass an object as in the following -

res.render('/dynamic',{
   user: {name: "Kennedy", age: "29"}
});

You'll receive a message - Hi, Kennedy. But if we don't pass any object or pass one with no user key, then we will get a signup link.


Include and Components

Pug provides a very intuitive way of creating components for a web page. For example, if you see a news site, the header having logo and categories are always fixed. Instead of copying that every view we create, we make use of the include feature.

Example

Following example shows how we use this feature -
Create 3 views with the following code -

div.header.
   I'm the header for this website.

HEADER.PUG

div.header.
   I'm the header for this website.

CONTENT.PUG

html
   head
      title Simple template
   body
      include ./header.pug
      h3 I'm the main content
      include ./footer.pug

FOOTER.PUG

div.footer.
   I'm the footer for this website.

Create a route for this as follows -

var express = require('express');
var app = express();

app.get('/components', function(req, res){
    res.render('content');
});

app.listen(3000);

include can also be used to add plaintext, CSS and JavaScript.

There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug.


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about how to Serve Static Files in ExpressJS.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain