Trying express-ejs-layout with Express.js
Contents
Express application with express-ejs-layout template
1 Environment
|
|
1 Install express.js
|
|
2 Simple application
|
|
Start server:
|
|
Then you can access http://localhost:3000/
to via browser.
Comparing to node.js simple web server, many step is hidden under the library.
3 Application using express-ejs-layouts
3.1 Install packages
ejs
and express-ejs-layouts
support express and ejs web page template.
|
|
3.2 Use ejs template
Code structure
├── main.js
├── controllers
│ ├── errorController.js
│ └── homeController.js
├── package-lock.json
├── package.json
├── public
│ ├── 404.html
│ └── 405.html
└── views
├── index.ejs
├── layout.ejs
└── partials
└── navigation.ejs
For using ejs template, main.js
calls:
|
|
views/layout.ejs
defines the template, like:
|
|
Then the other pages like views/index.ejs
supplement the <%- body %>
parts at layout.ejs
like:
index.ejs
|
|
3.3 Run server
As I installed nodemon
by npm i nodemon -S
and add below to package.json
,
"scripts": {
"start": "nodemon start"
},`
Start server by:
|
|
Then web page is generated by template.