Using pug template for building node applications

Reading Time: 2 minutes

Introduction

In this blog, we will look how we can use pug as a templating engine for building our node application. And how we can hold the dynamic content in our HTML pages using the templating engine. Here we begin!!! 

Setting up Nodejs

For using the templating engine we need the node to be installed in our system and then create the package.json file in your project with the help of following command :

npm init

After running this command, you will see the package.json file in your folder. And all the dependencies will get install in this file only.

For installing express , use

npm install nodejs express

For installing nodemon , use

npm install nodemon

What is pug?

Pug is a Node and browser-based template engine. It features a simpler syntax and compiles to HTML, allowing you to be more productive and your code to be more readable. Pug simplifies the creation of reusable HTML as well as the rendering of data from a database or API.

Syntax of using pug

Pug doesn’t use real html. It use minimimal html and custom template language which is extensible but generally offers only a set of things of operations you can do. But ‘if’ statements , ‘iterations’ will be included in this.

Syntax of pug :-

p # { name }

Installing PUG

Install PUG as a dependency in our Node application.

npm install pug

After installing, create the index.pug file inside the views folder having the ‘.pug’ as an extension. For getting the HTML template in your pug file, just simply write html in the code section you will get the pug structure of the html template.

Pug template example
Pug template example

Add the code in the body section

        h1#myHeading Pug template
        p.firstParagraph This is the first template!!!

Next step is to just add the pug file in the app.js file.

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

This means that we are telling express that you want to compile dynamic content using pug as a templating engine and where to find these templates. Save all the files and run the server using :-

npm start

Now go to the browser and run the https://localhost:3000. You will see the desired output

Conclusion

In this blog, we have learned how to use the templating engines and how we can install and integrate it in your node application.

Thank you for reading, if you really like the blog hit the like button, and to learn more, visit here

Written by 

Aanchal Agarwal is a Software Consultant at Knoldus. Her practice area is web development. She is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Her hobbies include watching movies, listening to music, and traveling. She likes to read books and explore new things.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading