Unlock the Power of Pug Templates

When it comes to building web pages, HTML is the foundation, but it can be limiting when trying to reuse page pieces across your website. That’s where Pug comes in – a high-performance template engine that makes it easy to reuse and create dynamic content.

What is Pug?

Pug is a templating engine that’s heavily influenced by HTML and implemented with JavaScript for Node.js and browsers. With ports available for other languages like Java, Python, and Ruby, Pug is a versatile tool that simplifies the creation and reuse of HTML code. Its easy syntax and flexibility make it a popular choice among developers.

Putting Pug into Practice

In this article, we’ll dive into how Pug works by creating a template from scratch. We’ll use Bootstrap’s Album example as our inspiration, and fetch data from the Random User Generation API to create a dynamic page.

Setting Up

To get started, you’ll need Node.js and npm installed on your machine. Create a new folder and run the following commands to initialize your project:

npm init
npm install express axios pug

Organizing Your Files

Create the following folders and files:

  • views/ – for your Pug templates
  • includes/ – for breaking down page pieces into reusable components
  • mixins/ – for storing reusable blocks of Pug code
  • index.js – for setting up your Express server

Creating Your First Pug Template

Let’s start with the card mixin, _thumbCard.pug. This template will display user information fetched from the Random User API. Here’s the code:


mixin thumbCard(user)
.col-md-4
.thumbnail
svg(width='100%', height='100%')
rect(x='0', y='0', width='100%', height='100%')
text(x='50%', y='50%', text-anchor='middle')= user.name.first + ' + user.name.last
.caption
h3= user.location.street
p View
p Edit

Including Files and Using Mixins

Next, let’s create the header, footer, and jumbotron Pug files. We’ll use the include keyword to import these files into our layout template.

Layout and Index Templates

The layout template will include our header, jumbotron, and footer files. The index template will extend from the layout template and iterate over the list of users, calling the card mixin for each user.

Index.js and Running the App

Finally, let’s set up our Express server and default route in index.js. Run the app with node index.js and view the results at http://localhost:3000.

Conclusion

Pug is a powerful templating engine that makes it easy to create dynamic web pages. By breaking down your page into smaller, reusable pieces, you can simplify your development process and create more efficient code. With Pug, the possibilities are endless. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *