DEV Community

Lord Neic
Lord Neic

Posted on

Basic Usage of Pug Templating Engine

Introduction

Pug is a template engine for Node.js that allows for clean, readable code for generating HTML. In this guide, we'll go over basic usage, syntax, and examples.

Table of Contents

  1. Installation
  2. Basic Syntax
  3. Simple Examples

Installation

To start using Pug, you can install it via npm:

npm install pug
Enter fullscreen mode Exit fullscreen mode

Basic Syntax

Pug syntax is fairly straightforward:

  • Tags are written as plain text, without angle brackets.
  • Text content follows the tag after a space.
  • Nesting is accomplished through indentation.
html
  head
    title My Page
  body
    h1 Hello, world!
Enter fullscreen mode Exit fullscreen mode

This will generate:

<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Simple Examples

Interpolation

You can use #{variable} to interpolate variables.

- var name = "John"
p Hello, #{name}!
Enter fullscreen mode Exit fullscreen mode

Conditionals

Pug allows you to use if-else conditions.

- var user = true
if user
  p Logged in
else
  p Not logged in
Enter fullscreen mode Exit fullscreen mode

Loops

You can iterate over arrays or objects.

- var items = ['Apple', 'Banana', 'Cherry']
ul
  each item in items
    li= item
Enter fullscreen mode Exit fullscreen mode

Top comments (0)