Title: Using Pug with Express.js
Pug (formerly known as Jade) is a powerful template engine for Node.js that allows you to write dynamic HTML more efficiently. This chapter covers how to use Pug with Express.js to create dynamic content, manage layouts and partials, and implement best practices in your Express.js applications.
A. Introduction to Pug Template Engine
Pug is a template engine that simplifies writing HTML by providing a concise syntax that eliminates the need for closing tags and reduces the amount of code. Pug allows you to create reusable templates, extend layouts, and embed JavaScript logic within your HTML.
-
Key Features:
- Indentation-based syntax, similar to Python.
- Supports template inheritance, making it easy to reuse code.
- Enables embedding of JavaScript code directly within templates.
-
Example of Pug Syntax:
//- layout.pug doctype html html head title= title body block content //- index.pug extends layout block content h1 Welcome to #{title} p This is an example of using Pug with Express.js.
B. Setting Up Pug with Express.js
Setting up Pug in an Express.js project is straightforward. You need to install Pug, configure the view engine, and define the directory where your templates are stored.
-
Steps to Set Up Pug:
-
Install Pug:
npm install pug -
Configure Express.js to Use Pug:
const express = require("express"); const path = require("path"); const app = express(); // Set Pug as the view engine app.set("view engine", "pug"); // Define the directory where the templates are stored app.set("views", path.join(__dirname, "views")); app.get("/", (req, res) => { res.render("index", { title: "Home Page" }); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); -
Create Your Pug Templates:
- Create a
viewsdirectory in your project root. - Add a file
index.puginside theviewsdirectory:h1= title p Welcome to your Express.js app with Pug!
- Create a
Explanation:
After configuring Pug as the view engine, theres.render()method renders theindex.pugtemplate and sends the HTML output to the client. -
C. Creating Dynamic Content with Pug
Pug allows you to create dynamic content by embedding variables, control flow statements, and loops directly within your templates.
-
Passing Data to Templates:
app.get("/about", (req, res) => { res.render("about", { title: "About Us", description: "This is an about page created using Pug.", }); }); -
Using Variables and Loops in Pug:
//- about.pug h1= title p= description ul each item in ['Express', 'Pug', 'Node.js'] li= itemExplanation:
Theabout.pugtemplate uses variables passed from the route handler and renders a list using theeachloop to iterate over an array.
D. Using Pug Layouts and Partials
Layouts and partials help in reusing code across different pages in your application, making it easier to maintain and update.
-
Creating a Layout Template:
//- layout.pug doctype html html head title= title link(rel='stylesheet', href='/styles.css') body header h1 My Website nav ul li: a(href='/') Home li: a(href='/about') About li: a(href='/contact') Contact block content footer p © 2024 My Website -
Extending the Layout in Other Templates:
//- contact.pug extends layout block content h2 Contact Us p Feel free to reach out to us via email.Using Partials:
- Partials are small pieces of reusable code that can be included in multiple templates.
//- header.pug header h1 My Website nav ul li: a(href='/') Home li: a(href='/about') About li: a(href='/contact') Contact- Include a partial in another template:
include header block content h2 Contact Us p Reach out to us via the contact form.Explanation:
Thelayout.pugtemplate serves as a base layout, while other templates likecontact.pugextend this layout. Partials likeheader.pugcan be included in any template to reuse the header code.
E. Best Practices with Pug
-
Use Template Inheritance:
Leverage layout templates and inheritance to avoid code duplication and improve maintainability. -
Keep Templates Organized:
Store your Pug templates in a structured directory, and separate different components into their own files for clarity. -
Minimize JavaScript Logic in Templates:
Avoid putting complex JavaScript logic inside Pug templates. Keep your templates focused on rendering HTML and leave the logic in your route handlers. -
Use Partials for Reusable Code:
When you find yourself repeating code across multiple templates, consider moving that code into a partial. -
Leverage Pug Mixins:
Use mixins to create reusable chunks of code that can be called with different parameters.
Conclusion
Pug is a powerful and expressive template engine that integrates seamlessly with Express.js. By mastering Pug, you can efficiently create dynamic web pages, manage layouts and partials, and follow best practices to build maintainable and scalable web applications.