

To use Pug with Express, we need to install it, There is a lot of ground to cover on this. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. With template engines, we can include loops, conditionals, and variables to make displaying dynamic content a breeze.Pug is a templating engine for Express. We can pass in an object in the second argument of res.render to pass in values that we want to display in the template. Rendering HTML response is easy if we use a template engine to do it. Since user.type in res.render is set to 'member'. In views/index.pug, then we get: 'User type is member' In index.js and: html head title= pageTitle body if user.type = 'anonymous' p User type is anonyomous else if user.type = 'member' p User type is member else p User type is admin Then we can create index.js in the same level as the views folder and add: const express = require('express') const app = express() app.use(express.json()) app.use(express.urlencoded() app.listen(3000, () => console.log('server started')) The title= and h1= are our tags and title and message are keys in which Express will use to get the values from in the object that we’ll pass to res.render. Inside the views folder, create an index.pug and then put: html head title= title body h1= message Since we chose to use Pug as our template engine, the template files should have the. views folder to be our templates folder. We can use the res.render method to render our variables to our templates.įirst, we create the views folder to store our templates as we set the. The command above will install pug view engine for us to use. To install the template engine library, we can run something like the following: npm install pug -save It’ll set the templates folder to the views directory of our app.Īlso, we can set the view engine we want to use by setting the view engine property as follows: app.set('view engine', 'pug') To set the templates folder, we can set the views property by writing the following: app.set('views', './views') To render template files, we can set the application settings. The default for the Express application generator is Jade, but we can use the other ones listed as well. We can use popular template engines with Express, like Pug, Mustache, and EJS. In this article, we’ll look at how to set the template engine of our app, and returning HTML responses. Templates are convenient and we can use them in a much more flexible way than HTML strings.

To render an HTML response with an Express route, we should return it as a template with the variable interpolated rather than return it directly as an HTML string.
