Approach to render dynamic content using Template Engine
- The below example uses Express and EJS templates to create a dynamic web application.
- It defines a route to render an HTML template that includes a form for user input.
- When the user submitst the form, the server processes the input, performs calculations (square and cube), and dynamically updates the rendered content with the results, demonstrating the feature of EJS for injecting dynamic data into the HTML template.
Example: Below is an example of rendering dynamic content in Node.js using templates.
HTML
<!DOCTYPE html> < head > < link rel = "stylesheet" href = "/styles.css" > < title >Node Template App</ title > </ head > < body > < h1 style = "color: green;" >w3wiki</ h1 > < h3 >Render dynamic content in Node.js using templates </ h3 > < form action = "/calculate" method = "post" > < label for = "number" >Enter a number:</ label > < input type = "number" id = "number" name = "number" required> < button type = "submit" >Calculate</ button > </ form > <% if (result) { %> < p >Square: <%= result.square %></ p > < p >Cube: <%= result.cube %></ p > <% } %> </ body > </ html > |
CSS
/* styles.css */ body { font-family : Arial , sans-serif ; text-align : center ; margin : 40px ; } form { margin-top : 20px ; } p { font-weight : bold ; color : green ; } |
Javascript
// app.js const express = require( 'express' ); const bodyParser = require( 'body-parser' ); const path = require( 'path' ); const app = express(); const port = 3000; app.set( 'view engine' , 'ejs' ); app.use(express.static(path.join(__dirname, 'public' ))); app.use(bodyParser.urlencoded({ extended: false })); app.get( '/' , (req, res) => { res.render( 'index' , { result: null }); }); app.post( '/calculate' , (req, res) => { const number = parseInt(req.body.number); const square = Math.pow(number, 2); const cube = Math.pow(number, 3); res.render( 'index' , { result: { square, cube } }); }); app.listen(port, () => { console.log(`Server is running at http: //localhost:${port}`); }); |
To run the application, we need to start the server by using the below command.
node app.js
Output:
Render dynamic content in Node using Template Engines
In Node.js, the rendering of dynamic content using Templates like EJS, Handlebars, and Pug consists of embedding dynamic data and logic directly into the HTML files. In this article, we will use the EJS Template Engine to render dynamic content in Node.js using Templates.
We will explore the practical demonstration of the concept in terms of example and output.
Table of Content
- Why Use Templates?
- Popular Template Engines for Node.js
- Steps to render dynamic content in Node.js using Template Engine
- Approach to render dynamic content using Template Engine