[Note] Node.js + express + EJS


Posted by urlun0404 on 2022-12-06

EJS是Embedded JavaScript的縮寫,是一種可以用JavaScript語法快速產生HTML樣板的樣板語言(template language)模組,同樣也需要用npm下載安裝。


因為EJS是用來產生HTML樣板的語法,所以所有 .html 檔案都會被 .ejs 檔案替換,以下示範如何在伺服器端渲染EJS檔案:

  • .ejs 檔案都必須放在根目錄底下的 view資料夾。
  • 伺服器檔案內,用 res.render('index.ejs') 代替 res.sendFile()。
  • 拿到參數後,可如下以 res.render('index.ejs', { product } ) 語法將取得的參數傳入EJS檔案
/* app.js */
const express = require('express');
const app = express();
const ejs = require('ejs');

// middleware
app.use(express.static('public'));

// routing
app.get('/', (req, res) => {
    res.render('index.ejs');
})

app.get('/products/:product', (req, res) => {
    const { product } = req.params;
    res.render('product.ejs', {product})
})

app.listen(3000, () => {
    console.log('The server is running on port 3000')
});


EJS檔案就和一般的HTML檔案沒什麼不同,唯一的差異在於,因為會用JavaScript拿取參數或寫一些程式碼,所以需要用到 <% %> 語法:

  • 使用JavaScript語法:<% /* JavaScript 一般語法*/ %>
  • 使用值會改變的JavaScript變數:<%= /* JavaScript 變數*/ %>
// /views/product.ejs
<html lang="en">
    <head>
        < !-- ... -->
        <link ref="stylesheet" href="styles/styles.css"/>
        <title>Product</title>
    </head>
    <body>
        <h1><%= product %></h1>
    </body>
</html>

或者比較複雜的迴圈語法可以這樣寫:

<table>
    <tr>
        <th>name</th>
        <th>rating</th>
        <th>popularity</th>
    </tr>
    <% languages.forEach(lang => { %>
        <tr>
            <td><%= lang.name %></td>
            <td><%= lang.rating %></td>
            <td><%= lang.popularity %></td>
        </tr>
    <% }); %>
</table>



最後再整理一下有關EJS檔案的使用方式:

  1. 在根目錄底下的views資料夾放置 .ejs 檔案;
  2. .ejs 檔案替代 .html 檔案;
  3. 伺服器端的語法都跟平常使用express差不多,唯一要注意的是若要渲染EJS檔案,要用 res.render() 代替 res.sendFile()
    • 一般渲染: res.render('index.ejs')
    • 傳參數渲染: res.render('show.ejs', { username, account })
  4. EJS檔案內容的語法和平常HTML檔案的語法大同小異,唯一差別在於如何寫入JavaScript語法:
    • <% /* JavaScript 語法 */ %>
    • <%= /* 值會改變的JavaScript變數 */ %>



References
Embedded JavaScript templates @npm
2022網頁開發全攻略(HTML, CSS, JavaScript, React, SQL, Node, more)


#Backend #node.js #Express #EJS







Related Posts

DAY42:Consecutive strings

DAY42:Consecutive strings

ModernWeb'21 隨筆

ModernWeb'21 隨筆

SQL & NoSQL

SQL & NoSQL


Comments