loading...
Cover image for IMPLEMENTING PUG AS YOUR TEMPLATE ENGINE IN YOUR NODE/EXPRESS PROJECT

IMPLEMENTING PUG AS YOUR TEMPLATE ENGINE IN YOUR NODE/EXPRESS PROJECT

mabrouk__a profile image Akinsola Mubarak ・2 min read

It is assumed that you have some knowledge in Node.js and Express for you to really understand this article.

NB: This does not include your programming logic in your express files, it just shows how to install, implement and render your page on the browser

Pug is an HTML templating engine, which means you can write much simpler Pug code, which Pug compiler will compile into HTML code, that browser can understand.
Implementing it into your project can be quite easy and it is makes your code concise and easy to read and follow through. Pug is just one of the many template engines available, and just to mention a few, we have EJS, HANDLEBARS, MUSTACHE etc.

First, Pug can be installed from your computer terminal or directly from your terminal in VS code!

Installing Pug

You install the Pug template engine with the above command (npm install --save pug) and node does the installation in no time.
From then on, you must have had an app.js file in your project. Now, it gets a little tricky, why? Because you don't have to require pug from node module with 'require' keyword.

You simply use it in your project such like:

Alt Text

The 'View Engine' above tells express which template engine that is being used in the project. If you choose to use any other template engine, it wouldn't be 'pug' you put above, rather, it would be your chosen engine.

Now, let's look at the code below:
Alt Text

And as to regards the 'Views', it tells express where to find our views (Our html pages), however the default setting is basically our main directory and the 'Views' folder (You could check the docs for more understanding).
If you would put your html pages in another folder which is not called 'Views', maybe your choose to name it 'shows', then you have to set it such like:

Alt Text

This way, you have successfully brought in pug into your application. Now when it gets to the point of serving your page.To serve your page in any of your javascript file, you do this below:

Alt Text

Now, You see the 'shop' above. don't be shocked. This is just the name of the file where I have the html page I would be rendering. It could have been 'shop.pug' as shown below.

Alt Text

So you can decide to add the extension '.pug' or choose not,it would still work regardless.

Discussion

pic
Editor guide