June 28, 2024

ExpressJS: Pug Template Engine Integration With Examples

The previous post ExpressJS Template Engines Introduction gives an introduction to template engines that can be used with Express.js. In this article we'll see how to use Pug template engine and its integration with Express.js.

Installing Pug

You can install Pug by using the following command.

npm install pug

Settings in Express.js for using Pug

You need to configure Pug as the view engine in Express.js app.

app.set('views', './views')

This setting sets the views directory in the application root directory as the location where template files are saved. Template engine will search this directory to locate the template that has to be transformed.

app.set('view engine', 'pug')

This setting sets pug as the template engine.

Writing Pug template

If you have used express-generator to create project structure you should already be having a views folder or you can create a views folder with in the app root directory and with in the view folder create a new file that has the extension .pug.

Pug templates don't use the full HTML tags, you just need to give the element name followed by the content. Ensure proper indentation for nested elements.

views\home.pug

doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    title #{pageTitle}
    link(rel="stylesheet", href="/css/main.css")
  body
    div#view.main
      h2.header #{heading.toUpperCase()}
      p= message

Some important points to note here-

  • To define an ID you can use #idname syntax.
    	div#view
    	
  • CSS classes may be defined using a .classname syntax
    div#view.main
    h3.header
    
    With the div main is the class that is used. With h3 element header class is used.
  • There are 3 placeholders in the template pageTitle, heading and message. You can either use #{} for a variable or equal sign (=) for getting the values for these variables.
    The code in between #{ and } is evaluated, escaped, and the result buffered into the output of the template being rendered. You can use JavaScript expression which can be evaluated.
    h2.header #{heading.toUpperCase()}
    

public\css\main.css

CSS used for styling.

.main{
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

.header{
  width: 100%;
  height: 3rem;
  text-align: center;
  background-color: #6d70a8;
  padding: 1 2rem;
  color: antiquewhite;
}

app.js

const express = require('express');

const app = express();

const port = 3000;
const path = require('path');

// To serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.get('/', (req, res) => {
    res.render('home', {pageTitle: 'MyPage', heading: 'Pug Template Example',
    message: 'Hello From Pug Template Engine'});
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Some important points to note here-

  • Properties are set for template engine using app.set() method.
  • In res.render() method template name is passed as the first parameter and as a second parameter values are set for the variables in the template.
  • Using the built-in middleware express.static() path to public directory is set where static files are stored. That is why, in the Pug template, you could link to stylesheet by giving the path relative to public.
    link(rel="stylesheet", href="/css/main.css")
    

This is the generated HTML that you can view by going to page source.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MyPage</title>
    <link rel="stylesheet" href="/css/main.css">
  </head>
  <body>
    <div class="main" id="view">
      <h2 class="header">PUG TEMPLATE EXAMPLE</h2>
      <p>Hello From Pug Template Engine</p>
    </div>
  </body>
</html>

That's all for the topic ExpressJS: Pug Template Engines Integration With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment