Skip to main content
Base Platform  /  Code Snippet Archive

Code Snippet & Reference Library

Battle-tested, copy-pasteable snippets across PHP, Python, JavaScript, VB.NET, SQL and Bash — compiled from real SaaS engineering sessions.

469
Snippets Indexed
2
PHP
0
JavaScript
7
Python
✕ Clear

Showing 2 snippets · Pug

Clear filters
SNP-2025-0156 Pug code examples programming 2025-04-19

How Can You Leverage Pug for Efficient and Maintainable HTML Templating in Your Projects?

THE PROBLEM

Pug, formerly known as Jade, is a powerful templating engine for Node.js that allows developers to write HTML in a concise and elegant manner. With its clean syntax and ability to integrate seamlessly with various frameworks, Pug has become a popular choice among web developers looking for efficiency and maintainability in their HTML code. In this post, we'll explore how you can leverage Pug to improve your web development projects, focusing on its core features, practical implementation techniques, and best practices.

Pug offers several advantages over traditional HTML coding:

  • Cleaner syntax that reduces boilerplate code
  • Support for mixins and inheritance, promoting code reuse
  • Integration with various back-end frameworks
  • Dynamic content rendering capabilities

This section will provide a historical overview of Pug's evolution, its core features, and why it stands out in today's web development landscape.

Pug was originally created as Jade in 2010, gaining popularity due to its unique syntax that allowed for the creation of HTML documents without the need for closing tags and excessive attributes. In 2016, the project was renamed Pug to avoid trademark issues. Since then, it has undergone significant updates and improvements, solidifying its place as a go-to templating engine for Node.js applications.

To fully harness the power of Pug, it's crucial to understand its core technical concepts:

  • Indentation-Based Syntax: Pug uses indentation to define the structure of the HTML document, similar to Python's whitespace sensitivity.
  • Mixins: These are reusable code snippets in Pug that allow for the definition of templates that can accept arguments.
  • Interpolation: Pug supports JavaScript expressions within templates, making it easy to render dynamic content.
💡 Tip: Familiarize yourself with Pug's syntax rules, as they differ significantly from traditional HTML.

To get started with Pug, you'll need to install it in your Node.js application. Here’s how you can set it up:

npm install pug

Next, you can configure Pug in your Express application:

const express = require('express');
const path = require('path');
const app = express();

// Set Pug as the templating engine
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

app.get('/', (req, res) => {
    res.render('index', { title: 'Home', message: 'Welcome to Pug!' });
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Understanding Pug's syntax is crucial for effective templating. Here’s a simple example demonstrating basic Pug syntax:

doctype html
html
    head
        title= title
    body
        h1= message
        p Welcome to your Pug template!

This example illustrates how to create a basic HTML document using Pug's indentation-based syntax.

Pug also supports advanced features that improve code organization and reusability:

  • Mixins: Create reusable components.
  • Extends: Inherit from other templates.
  • Conditionals and Loops: Dynamically generate HTML based on data.

Here’s an example of using mixins:

mixin button(text, type='button')
    button(type=type) #{text}

+button('Click Me')
+button('Submit', 'submit')

Security is paramount when developing web applications. Here are some best practices when using Pug:

  • Sanitize User Input: Always sanitize data before rendering it in your templates to prevent XSS attacks.
  • Use the Escape Syntax: Use the escape syntax to safely render user-generated content.

Example of escaping user input:

p= escape(userInput)

When choosing a templating engine, it's essential to compare Pug with alternatives like EJS and Handlebars:

Feature Pug EJS Handlebars
Syntax Indentation-based HTML with tags HTML with expressions
Code Reuse Mixins and extends Includes Partials
Performance Fast with caching Good Good

This comparison helps determine the best templating engine for your project's needs.

If you're new to Pug, follow these quick steps to get started:

  1. Install Pug using npm.
  2. Set it up with your Node.js application.
  3. Create your first Pug template.
  4. Render the template in your application.

By following this guide, you can quickly get your first Pug-based application up and running.

1. What is the difference between Pug and HTML?

Pug uses an indentation-based syntax that eliminates the need for closing tags and reduces boilerplate code, making it more concise and readable than traditional HTML.

2. Can Pug be used with front-end frameworks?

Yes, Pug can be integrated with front-end frameworks like React and Vue.js, although it's primarily used on the server side with Node.js.

3. How do I debug Pug templates?

Use tools like Pug Linter or integrate your IDE's linting capabilities to catch syntax errors and improve template quality.

4. Is Pug suitable for large applications?

Absolutely! Pug’s features like mixins and template inheritance make it scalable and maintainable for large codebases.

5. Can I use Pug with static site generators?

Yes, Pug can be used with static site generators like Eleventy or Gulp to create dynamic HTML pages.

Pug is a powerful templating engine that can significantly enhance your web development workflow by providing a clean, efficient, and maintainable approach to HTML templating. By leveraging its advanced features and adhering to best practices, you can create scalable web applications that are both performant and secure.

As you continue to explore Pug and integrate it into your projects, remember that practice and familiarity with its syntax and features will ultimately lead to mastery. Happy coding! 🚀

PRODUCTION-READY SNIPPET

As with any technology, developers may encounter common pitfalls when using Pug:

  • Indentation Errors: Ensure consistent use of spaces or tabs to avoid syntax errors.
  • Mixins Not Rendering: Check for proper invocation of mixins with the correct syntax.

For example, failing to indent correctly might lead to unexpected HTML structure. Here’s a common mistake:

ul
    li Item 1
  li Item 2 // Incorrect indentation results in unexpected structure
⚠️ Warning: Always use a linter to catch indentation errors early in development.
PERFORMANCE BENCHMARK

To ensure your Pug templates are performant, consider the following techniques:

  • Template Caching: Cache compiled Pug templates to reduce rendering time.
  • Minify Output: Use Pug’s built-in options to minify HTML output.

Here’s how to enable caching in an Express application:

app.set('views', path.join(__dirname, 'views'));
app.set('view cache', true); // Enable template caching
Open Full Snippet Page ↗
SNP-2025-0139 Pug code examples programming 2025-04-19

How Can You Leverage Pug's Features to Enhance Your Modern Web Development Workflow?

THE PROBLEM

Pug, formerly known as Jade, is an elegant template engine for Node.js that enables developers to write HTML in a more streamlined and efficient way. As web development continues to evolve, understanding how to effectively use Pug can significantly enhance your workflow, making your code cleaner and more maintainable. In this post, we will explore the various aspects of Pug, from its core concepts to advanced features, and how it can optimize your web development process.

Pug was created as a solution to the complexities of writing HTML, especially when it comes to repetitive structures. It was designed to make the code more readable and maintainable by removing unnecessary syntax and providing powerful features like mixins and conditionals. Over time, Pug has gained popularity due to its seamless integration with Node.js and frameworks like Express, making it a go-to choice for many developers.

Understanding the fundamentals of Pug is essential for leveraging its full potential. Here are the core concepts you should be familiar with:

  • Indentation-Based Syntax: Pug uses indentation to define elements, which eliminates the need for closing tags. This can significantly reduce the amount of code you write.
  • Mixins: These are reusable templates that allow you to define a block of code once and use it multiple times, reducing redundancy.
  • Interpolation: Pug supports string interpolation, allowing you to inject JavaScript expressions directly into your HTML.
  • Conditionals and Loops: Pug allows you to include JavaScript logic in your templates, enabling dynamic content generation.
💡 Quick Start Guide: To start using Pug, you need to install it via npm. Run npm install pug in your project directory.

Here’s a simple example to demonstrate how to create a Pug template:

doctype html
html
  head
    title My Pug Template
  body
    h1 Welcome to Pug
    p This is a simple Pug template.

When compiled, this will produce the following HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>My Pug Template</title>
  </head>
  <body>
    <h1>Welcome to Pug</h1>
    <p>This is a simple Pug template.</p>
  </body>
</html>

Pug is rich in features that can streamline your development process. Let's dive into some advanced features:

Mixins

Mixins allow you to define a block of reusable code. Here’s how to create a mixin for a button:

mixin button(text, url)
  a(href=url) #{text}

+button('Click Me', 'https://example.com')

This code will render a link styled as a button. Mixins can take parameters, which makes them highly versatile.

Conditionals

You can include conditionals in your templates to render different content based on specific conditions:

if user.isAdmin
  p Welcome, Admin!
else
  p Welcome, User!

This snippet checks if the user is an admin and displays the appropriate message.

Loops

Loops can be used to iterate over arrays or objects, making it easy to generate lists:

ul
  each item in items
    li= item

This creates an unordered list from the items array.

Best Practices: Keep your Pug files organized by separating them into components and using partials for reusability.

Here are some additional best practices:

  • Use Comments: Comment your Pug files to explain complex logic or structure.
  • Modular Templates: Break your templates into smaller components. This promotes reusability and easier maintenance.
  • Consistent Naming Conventions: Use clear and consistent naming conventions for your variables, mixins, and templates.

When considering frameworks, it’s crucial to understand how Pug fits within the broader ecosystem:

Feature Pug React Vue Angular
Template Syntax Indentation-based JSX HTML-based HTML-based
Reactivity No Yes Yes Yes
Learning Curve Low Medium Medium High
Use Cases Server-side rendering Single Page Applications Single Page Applications Enterprise Applications

Security is paramount when developing web applications. Here are some security best practices when using Pug:

  • Sanitize Input: Always sanitize user input to prevent XSS attacks. Pug has built-in escaping mechanisms to help with this.
  • Use HTTPS: Ensure your application is served over HTTPS to protect data in transit.
  • Regular Updates: Keep Pug and its dependencies up to date to protect against vulnerabilities.

1. What are the advantages of using Pug over traditional HTML?

Pug simplifies HTML writing with its indentation-based syntax, reduces code verbosity, and allows for reusable components through mixins.

2. Can Pug be used with client-side frameworks?

While Pug is primarily a server-side template engine, it can be used in conjunction with client-side frameworks, although it's more common in server-rendered applications.

3. How do you handle dynamic data in Pug?

Dynamic data can be injected into Pug templates using JavaScript variables, allowing you to create content based on application state.

4. What is the difference between Pug and EJS?

Pug offers a cleaner, more concise syntax with advanced features like mixins, whereas EJS uses traditional HTML syntax with embedded JavaScript code.

5. Is Pug suitable for large-scale applications?

Yes, Pug is suitable for large applications, especially when organized into modular components and optimized for performance.

In conclusion, Pug is a powerful template engine that can greatly enhance your web development workflow. Understanding its features, best practices, and potential pitfalls can lead to cleaner, more maintainable code. As you leverage Pug in your projects, remember to keep performance, security, and organization in mind to fully harness its capabilities. Whether you're building small applications or large-scale systems, mastering Pug can be a significant asset in your development toolkit.

PRODUCTION-READY SNIPPET

While Pug can improve your workflow, there are common pitfalls to be aware of:

  • Indentation Errors: Pug relies heavily on indentation. Mixing spaces and tabs can lead to unexpected results. Always use a consistent indentation method.
  • Missing Mixins: Forgetting to define a mixin before using it can cause runtime errors. Make sure all mixins are defined at the top of your Pug file.
  • Improper Variable Scopes: Be cautious about variable scoping. Variables defined inside conditionals or loops may not be accessible outside of those blocks.
PERFORMANCE BENCHMARK

When working with Pug, performance is crucial, especially for large applications. Here are some optimization tips:

  • Cache Compiled Templates: Use Pug’s built-in caching mechanism to cache compiled templates and reduce rendering time.
  • Avoid Deep Nesting: Keep your template structure flat. Deeply nested structures can slow down rendering.
  • Limit Dynamic Content: Minimize the use of runtime computations within your templates, as they can lead to performance overhead.
Open Full Snippet Page ↗