Advantages of using Template Engines
- Template engines improves developer’s productivity. Improves readability and maintainability.
- Templates are easy to replicate; you can take them from one specific place instead of copying and pasting them every time;
- Template engines are used when you want to rapidly build web applications that are split into different components.
- emplates also enable fast rendering of the server-side data that needs to be passed to the application. For example, you might want to have components such as body, navigation, footer, dashboard, etc.
- Some templating engines can make pregeneration a bit easier and pre-compilation to make them faster
Example: Here is the basic example of ejs template engine:
Javascript
// Set express as Node.js web application // server framework. // To install express before using it as // an application server by using // "npm install express" command. const express = require( 'express' ); const app = express(); // Set EJS as templating engine app.set( 'view engine' , 'ejs' ); const server = app.listen(4000, function () { console.log( 'listening to port 4000' ) }); |
Steps to run the program:
node index.js
Output:
What are template engines in Express, and why are they used?
A Template Engine simplifies the use of static templates with minimal code. During runtime on the client side, variables in the template are replaced with actual values. These engines help developers create templates for web pages, written in a markup language with placeholders for dynamic content. When rendered, these placeholders are substituted with real data, producing a dynamic document.
We will learn about the following template engines and why they are used:
Table of Content
- EJS
- Pug
- Mustache
- Why Template Engines are Used?
- Advantages of using Template Engines
EJS:
EJS, or Embedded JavaScript Templating, is a templating engine utilized in Node.js. This engine assists in the creation of HTML templates with minimal code, allowing the injection of data into the template on the client side to generate the final HTML output. EJS serves as a straightforward templating language, utilizing plain JavaScript to generate HTML markup. Additionally, it facilitates the embedding of JavaScript into HTML pages. To initiate the use of EJS as a templating engine, installation is required via the provided command.
npm install ejs --save
Contact Us