DEV Community

Jefferson Duong
Jefferson Duong

Posted on

Lets Learn Pug!

What's PUG?

First of all, what IS pug? Pug is a template engine to write our HTML documents using a blend of JavaScript and HTML's syntax. This blend allows us to do things that are utilized in both JavaScript and HTML, such as creating and storing variables, creating functions, interpolating variables, creating and filling HTML documents with the exclusion of element tags. Using pug allows for cleaner code, since element tags are excluded, while maintaining the flexibility of JavaScript by allowing us to implement variables and functions within the same file.

The exclusion of element tags allows for much cleaner code. At first, I was a bit confused and spent more time on making sure the indents were in the proper place, but after adjusting I don't think I would go back to traditionally typing in an HTML file. The exclusion of tags also made it easier to debug due to lost closing tags, or any missing characters. Pug also allows for simple element creation and adding IDs or classes. A div with the class name of "hello" would simply be typed as '.hello'.

.hello.anotherClass.andAnotherOne
        h1 I have created a div that has 3 classes, and an h1 element inside of that div!
Enter fullscreen mode Exit fullscreen mode

However, due to the engine not using any tags, or brackets, there is a large emphasis on indents. Instead of placing content within tags, they are simply indented to show which element is the child/parent.

At first, I wasn't quite sure what to do with any kind of JavaScript functionality in an HTML document while I was trying to replicate Medium's website as a classwork assignment. However, after creating it and going back and seeing that there were multiple elements repeated, I found a perfect spot to implement some JavaScript code to reduce lines in my HTML.

In this code segment, the code that you see above the for loop was repeated 5 times to produce 5 articles. Instead of creating 5 blocks of the same code, a for loop was created to create the same article 5 times. Since pug can create variables, an array can be created to store the links, and the loops can create these elements with those URLs!

I have only begun to scratch the surface of pug, but I look forward to using it more!

Top comments (3)

Collapse
 
codingnspace profile image
Pearl McPhee

Awesome post, Jefferson!

Collapse
 
zfleischmann profile image
Zakk

Great post!

Collapse
 
keshavdutt profile image
keshavdutt • Edited

Well, that's some quality article. Meanwhile, I have also written a complete tutorial on Pug, have a look into this also Pug Tutorial