Template Engines (pug, hbs, EJS) in Node js | Add Dynamic Content in Express Js
A template engine enable you to use static template files in your application. At runtime, the template engine replace variables in a template file with actual values, and transforms the template into a HTML file sent to the client. This approach makes it easier to design an HTML page.
pug | is a template engine that user case sensitive syntax for writing HTML |
hbs | Express handlebars template engine with multiple layouts, blocks and cached partials. |
EJS | Embedded JavaScript(EJS) is a templating engine used by nodeJS to create HTML template with minimal code |
const express = require("express");const path = require('path');const app = express();const port = 7000;const staticpath = path.join(__dirname,"../");console.log(staticpath)// to set the view enginapp.set("view engine", "hbs");app.use(express.static(staticpath));// template engin rootapp.get("",(req, res)=>{res.render('indexFile');})app.get("/", (req,res)=>{res.send("hello this issdf express");});app.listen(port, ()=>{console.log("listening...",port);})
index.js<!DOCTYPE html><html lang="en"><head><title>Document</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"></head><body><h1>this is indexFile.hbs</h1><button class="btn btn-primary">btn1</button><button class="btn btn-primary">btn1</button><button class="btn btn-primary">btn1</button><button class="btn btn-primary">btn1</button><button class="btn btn-primary">{{dynamic}}</button><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script></body></html>
const express = require("express");const path = require('path');const app = express();const port = 7000;const staticpath = path.join(__dirname,"../");console.log(staticpath)// to set the view enginapp.set("view engine", "hbs");app.use(express.static(staticpath));// template engin rootapp.get("",(req, res)=>{res.render('indexFile',{dynamic:"this is dynamic button"});})app.get("/", (req,res)=>{res.send("hello this issdf express");});app.listen(port, ()=>{console.log("listening...",port);})
set path for changing directory, means 'views' directory rename with 'newdir'
const rename = path.join(__dirname,"../newdir");app.set("views", rename);
Post a Comment