A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML. The following figure illustrates how template engine works in Node.js.
As per the above figure, client-side browser loads HTML template, JSON/XML data and template engine library from the server. Template engine produces the final HTML using template and data in client’s browser. However, some HTML templates process data and generate final HTML page at server side also.
There are many template engines available for Node.js. Each template engine uses a different language to define HTML template and inject data into it.
The following is a list of important (but not limited) template engines for Node.js
Advantages of Template engine in Node.js
- Improves developer’s productivity.
- Improves readability and maintainability.
- Faster performance.
- Maximizes client side processing.
- Single template for multiple pages.
- Templates can be accessed from CDN (Content Delivery Network).