A Better Way to Write HTML, PugJS

Bilge Çimen
Sep 2, 2018 · 2 min read

Pug is a node library that enables us to render html files from pug syntaxed files. To install pug npm install pug .

There are three features that makes the pug best rendering library for me.

Easy and Short Syntax

HTML File
Pug File

Above there are two pieces of code one is written in html and other is written in pug. Pug could look hard to understand but after writing 3 hours of pug it becomes the easiest thing in the world. You can easily see how short and easy to write things in pug.

Dynamic Content

Since PugJS renders our pug syntaxed files to html files in runtime we can easily change the content of our pages from backend by parsing whatever we want to pug as parameters.

Rendering Pug in NodeJS
parameters.pug File

Above you can see the implementation of PugJS in NodeJS. We render our parameters.pug file with the parameters user and title. In the pug file we put our title parameter to the title of the page. If the user is defined we create a h1 with username otherwise we create a h1 saying “No User”.

Note : every .pug should be in a folder named views in the same directory with the app/server.js file.

Inheritance and Code Re-usability

mainLayout File
child File

For the ones which have no idea about inheritance, its basically instead of copying pasting blocks of codes or properties we just inherit this blocks of codes from another file.

In the example above we create a mainLayout which we can use for every page we create and created blocks in it which enables us to change the content of the things in the indent of this blocks. You can think it as we copy the things in the indent of block styles in the child file to the indent of block styles in the mainLayout file. Instead of writing html head navbar etc.. in every page we just inherit it from our mainLayout.

Thanks for reading if you like the pug you can checkout its documentation from here.

If you have questions please don’t hesitate to ask them. Hope you liked this story.

Bilge Çimen

Written by

CS Student at Hacettepe University. Full Stack Developer. Security Enthusiastic

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade