Edge is a logical template engine for Node.js Edge is easy to use and you can write your javascript logic on .edge file.
I will be giving a step by step guild on how to use edge template with node.js. Let get started.
1. create a package with following command and give your suitable answers to the required questions.
npm init
Next , i will install express followed by edge with the npm library.
npm install express --save
npm install edge cors body-parser --save
2. confirm installation in your package.json file
{
"name": "tutorial",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express-edge": "^2.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
3. create a file app.js as the entry file specified initially and configure express . In my own file app.js
const path = require("path");
const express = require("express");
const bodyParser = require('body-parser');
const cors = require('cors');
const { config, engine } = require('express-edge');
const pageController = require('./controllers/pages-controller');
const app = express();
const port = process.env.PORT || "8111";
// Automatically sets view engine and adds dot notation to app.render
app.use(engine);
app.set('views', `${__dirname}/views`);
const app = express();
const port = process.env.PORT || "8111";
// Automatically sets view engine and adds dot notation to app.render
app.use(engine);
app.set('views', `${__dirname}/views`);
app.use(express.static('public'));
// middleware
app.use(bodyParser.urlencoded(({extended: false})));
app.use(bodyParser.json());
app.use(cors());
app.listen(port, () => {
console.log(`Listening to requests on ${port}`);
});
Note : i have set the views to the folder /views and my static folder public which will contain all static files . and partials folder which contain two files header.edge and footer.edge
Below is my directory structure. Copy the partials folder to the views
5. Generate route in app.js, i will add a get route for homepage
app.get("/", (request, response)=> {
response.render('home');
} );
6. populate content in home.edge file , Add partials .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
< @include('partials.header')
<p> this is my home page</p>
@include('partials.footer')
</body>
</html>
header.edge
<header> THIS IS COMING FROM HEADER</header>
footer.edge
<header> THIS IS COMING FROM HEADER</header>
node app.js
0 Comments