1. Cài đặt thư viện Template engine
1.1. Express Handlebars
-- https://www.npmjs.com/package/express-handlebars
-- Cài đặt:
1 |
npm install express-handlebars |
2. Tại main chính: ./src/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const path = require('path'); const express = require('express'); const handlebars = require('express-handlebars'); const app = express(); const port = 3000; //Static public link app.use(express.static(path.join(__dirname, 'public/'))); //Template engine app.engine('hbs', handlebars({ extname: '.hbs' })); app.set('view engine', 'hbs'); app.set('views',path.join(__dirname,'resources','views')); app.get('/', (req, res) => { res.render('home'); // res.send('<h1>Hello World!</h1>'); }) app.get('/news', (req, res) => { res.render('news'); }) |
3. Cấu trúc thư mục views
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
. ├── node_modules ├── src │ ├── app │ │ ├── controllers │ │ └── models │ ├── resources │ │ └── views │ │ ├── layouts │ │ │ └── main.hbs │ │ ├── partials │ │ │ ├── header.hbs │ │ │ └── footer.hbs │ │ ├── home.hbs │ │ └── news.hbs │ └── routes ├── package-lock.json └── package.json |
4. Tạo Layout
-- Tại file: ./src/resources/views/layouts/main.hbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href=""> </head> <body> {{> header}} {{{body}}} {{> footer}} </body> </html> |
-- Tại file: ./src/resources/views/partials/header.hbs
1 |
<h1>Header</h1> |
-- Tại file: ./src/resources/views/partials/footer.hbs
1 |
<h1>Footer</h1> |
-- Tại file: ./src/resources/views/home.hbs
1 |
<h1>HomePage</h1> |
-- Khi render bất kỳ một file nào, server sẽ render file main.hbs đầu tiên.
-- {{> header}} và {{> footer}} sẽ lấy từ header.hbs và footer.hbs trong partials
-- Sau đó file được render sẽ đi vào phần {{{body}}}, giả sử home.hbs
5. Render dữ liệu sang views
-- Tại nơi render, ví dụ: ./src/index.js
1 2 3 4 5 6 7 8 9 10 |
app.get('/', (req, res) => { res.render('home', { project: "Demo NodeJS", author: [ { name: "DuyCode", job: "developer" }, { name: "John", job: "designer" }, { name: "Peter", job: "marketing" }, ], }); }) |
-- Tại file: ./src/resources/views/home.hbs
1 2 3 4 5 |
<h1>{{project}}</h1> {{#each author}} <h3>{{this.name}} -- {{this.job}}</h3> {{/each}} |
-- Cách render đọc thêm tại: https://handlebarsjs.com/guide/