Try out some of the popular view engines in Nodejs project

Tram Ho

What is the view of the engine in Node.js?

The easiest way to understand the view engine in Node.js is like the Blade in Laravel. So the most basic definition, the view engine is the tool that helps us write HTML code in a shorter and simpler way than it normally can and reuse. In addition, it can import data from the server side and render the final HTML. Some common package view engines in the project NodeJS / Express can be listed as follows:

Today I will try some of the templates above to see which one is easier to use. Let’s start…

EJS

First to create a demo for this article we need to create a project base with ExpressJS. To create the fastest I use express-generator .

When running the command to create the project with the view engine, ejs we have the project with the following directory structure:

So with the above command, we have created a Project Express using available EJS view engine. This view engine is setup in the app.js file:

Next to illustrate how to use it, I will perform the basic layout of the site and render the data from the server. First we try to render the data from the server.

Edit routes/index.js file routes/index.js :

File views/index.ejs :

So we have implemented data transfer from server to view and rendered. In addition we can split the header, footer by adding header.ejs files, footer.ejs then include as follows:

Pug

Pug – formerly known as Jade, is also a popular view engine in Nodejs projects. To use it make the view engine set up as follows:

With the above example, we create pug files with the following content:

So with the same content we see how Pug’s writing is clear, concise and easy to understand. Pug works in much the same way as Python programming language ie using indent or white space. We don’t need to care if the card is open / closed because Pug will replace you.

Hbs (Handlebars.js)

To use this template we set the engine view to hbs . At the same time we have to register the blocks (in handlebarjs called partial) as follows:

With the above problem we will also create hbs files with the following content:

Conclude

So I have tried to use a few popular view engines in Nodejs project. And if you choose to develop the product, you choose Pug because it is very simple and easy to understand, and you choose the engine view for Nodejs project?

Share the news now

Source : viblo.asia