In express.js there are a number of options for view engines, or template languages as they might often be referred to as. I am somewhat partial to ejs which closely resembles the same syntax of html, but another popular option is pug that follows a syntax similar to languages like that of python.
I have all ready wrote a post on using the pug node.js npm package by itself, but in this post I will be writing on setting up pug in express.js so it can be used with the render response method.
To create a basic example of using pug with express.js and pug I would start out by creating a new folder, and doing and initialize a new npm package in the folder. After that I would install express and pug and save them to the package.json file. I will also want a view folder in which to place the *.pug files that I will be using with the express render method.
For this express pug example I will want to create a *.pug file to render in my views folder. So in the views folder I placed an index.pug file that looks like this:
The name of this file is what I will be passing to the res.render method in my express project when defining the logic for a given path.
back at the root name space of the project folder I created a basic.js file. In here I will be using express and setting pug as the view engine that is to be used.
It is also possible to pass local variables to a view with the render method. This is useful if the back end strip has some data that I want to have rendered into the html that will be sent back to the client. To do so I just need to pass an Object with the names of the variables as the key names and then they values as the properties. Inside the pug file I can then use those values in the rendering process.
So for this example I am once again creating a *.pug file in the views folder that will be used for this example. So I made a file that I called locals.pug that makes use of the pug syntax that is used to render values passed as local variables from express via the res.render method.
So then once again the process is more or less the same as before only now I am passing an object as the second argument to the res.render method that will contain the values that are to be used to render in locals.pug.