InterviewSolution
| 1. |
Explain Express.js Template Engine? |
|
Answer» A template ENGINE is used to write static code of HTML files. All of these template engines have their own language and are used to write the code for templates. When a client goes to any route which serves a template file, these template engines convert them in PURE HTML code and send them back to the client. This is a very efficient and fast way to generate HTML files at the server, instead of relying on FRONTEND client-side code through languages like Angular, React, or Vue. The popular template engines for Express are Pug, Handlebars, Mustache, and EJS. Let’s look into an example of Pug, which is one of the most popular templating engines. First create a new Node.js application by creating a directory and changing to it. Then initialize a package.json file with the npm init -y command. It will give all options as yes and if we don’t give it, we will have to manually type yes. Now, install express and pug into the node application by using the command npm i express pug in the terminal. Now, create a file server.js in the root directory and put the below code in it. Here, we are first importing express and then setting it to app. Now, with this app we are using pug as our view engine. After that we are having a GET function to /. Inside the GET function, the RES object is rendering the home. Lastly, we are listening to all incoming requests are LOCALHOST 3000. Now, create a views folder and inside it home.pug file. Now, in this file we will put a h1 and a p with content. Notice the coding style for pug, which is totally different compared to html. Now, go to http://localhost:3000/ and we will get the pug file rendered as html on the browser. |
|