29 September 2019

NodeJS ExpressJS: Template engines [EX-02]

Using template engines with Express
Pug (jade), Mustache, EJS
[1] Single page application (SPA)
 - Nội dung render trên front end
 - Không load lại trang
 - Tương tác với data dạng Json API

[2] Multiple page application
- Nội dung render trên server
- Load lại trang

https://expressjs.com/en/guide/using-template-engines.html
https://pugjs.org/api/getting-started.html
https://pughtml.com/
https://pugjs.org/language/iteration.html

npm install pug --save

Express server
app.js
const express = require('express')
const app = express()
const port = 3000

app.set('view engine', 'pug')
app.set('views', './views');

// GET method route
app.get('/', function (req, res) {
    res.render('index', {
        title: 'Hey',
        message: "ExpressJS"
    })
})

// GET method route
app.get('/users', function (req, res) {
    res.render('users/index', {
        users: [{
            id: 'ID291',
            name: 'David Zinn'
        }]
    })
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

views/index.pug
index.pug
html
  head
    title= title
  body
    h1= message

    a(href='/users') Users

views/users/index.pug
index.pug
ul
    each user in users
        li= user.id + ': ' + user.name

Command: node app.js
Url: http://localhost:3000/users
Kết quả: ID291: David Zinn

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang