InterviewSolution
| 1. |
What template engines can you use with express? |
|
Answer» We can use a lot of template engines in express, which are used to change a static file written in server to actual HTML content, to be displayed in the client browser. Some of the popular template engines, which works with express are below -
We will now look into examples of one of the popular template engines, which is EJS. The syntax of EJS is quite similar to HTML code and we can ALSO use dynamic content in it. First, we will go through the basic SETUP steps and create a new Node.js application by CREATING a directory and changing to it. Then will initialize a package.json file with the npm init -y command. Now, install express and EJS into the node application by using the command npm i express ejs in the terminal. Next, we will create a file index.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 the ejs as our view engine. After that we are having a get function to /. Inside the get function, we have a variable people first, containing an array of object people. Then we are using the res object to render a home component and passing people array to it. Lastly, we are listening to all incoming requests are localhost 3000. Once this is done, we will create a views folder and inside it home.ejs file. Now, in this file we will put an h1 and a p tag with content. Notice the coding style for EJS, is quite similar to that of an HTML code. Inside an ul tag, we are also looping through the people array, which we got from index.js and printing the name in li tags. Now, just go to http://localhost:3000/ and we will get the EJS file rendered as html on the browser. |
|