利用 Handlebars 樣板引擎,將 HTML 的內容拆到 Index.js 的路由外面。
伺服器要把網頁內容回應到瀏覽器前必須先透過 Handlebars 這個樣板引擎,也就是說,在產生畫面前,伺服器必須要先去做一些處理。
當 HTML 並沒有經過 CSS 的美化,所以看起來非常粗糙,這樣的東西是無法拿出去見人的!
Install step :
- Download and Install express-handlebars
- Setting about Use Handlebars of Setting with Express
- Use Express Handlebars
- Start project
— — — — — — — — — — — — — — — — — — — — — — — — — —
//Before Install have Detail of two important concepts :
ᕙ(˵ ಠ “ಠ ˵)ᕗ very very very Javasix . ❤️
佈局 和 局部樣板 / layout and partial template /
看網頁時候, 常常會很多頁面的地方是重複的, 因此將重複的部分編成一個檔案, 稱為 ‘ Layout ‘ 佈局 .
2. server 先透過handlebars 編譯成Html , 再傳回到Server .
3. handlebars 編譯過程’” 未經過route to respone “
佈局 / Layout 🇹🇼
藍色的部分是每個頁面的佈局(layout),因為不會改變, 所以可以將此編成一個Layouts 檔案.
局部樣板/ Partial Template 🇹🇼
可以根據每個頁面有所不同,所以屬於局部樣板(partial template)。
1. 安裝 Express-handlebars : 💠
Npm a lot tool ( package of templates )
$ npm i express-handlebars // "i" is mean install la
檢查版本 / check version ☑️
//when you insstall and than wanna check version , could be inspect from[ package.josn. ] find it ! amost on your project folder .
2. 設定 Template Engin : 🚒
- open your project of app.js
2. require(`express-handlebars`) ,並把它存成名為 exphbs
的變數:
3.Setting template :
alot wrtten just follow my pictures , this is rule …..( Never mind )
Javasix Expain :
Tell Express: 🇨🇾Please help me hand over’’ the model engine to express-handlebars’’ after loading .
// require express-handlebars here
const exphbs = require('express-handlebars')// setting template engine
app.engine('handlebars', exphbs({ defaultLayout: 'main' }))
app.set('view engine', 'handlebars')// routes setting
// ...
If you have confuse …. 😕. or. 😖 …. next have others good explain …
關於程式碼的解釋:
//資料來源 ALPHA CAMP 程式語言學校//. 🇹🇼 🇹🇼 🇹🇼 🇹🇼🇹🇼 👫
app.engine
:透過這個方法來定義要使用的樣板引擎,其中- 第一個參數是這個樣板引擎的名稱
- 第二個參數是放入和此樣板引擎相關的設定。
- 這裡設定了預設的佈局(default layout)需使用名為
main
的檔案。稍後我們再來建立這支main
檔案,並說明佈局的概念。 app.set
:透過這個方法告訴 Express 說要設定的view engine
是handlebars
。
以上都是 Express 的固定使用語法格式。
如此我們就完成了 handlebars 在 Express 使用前的設定。
3. 建立 views 和 layouts 資料夾 📁 and …..2 file
3–1. [main.handlebars] and [index.handlebars ]
把副檔名為 .handlebars
的檔案經過編譯轉換之後,才會變成真正的 HTML 回傳到瀏覽器讓使用者瀏覽。
`.handlebars` for handlebars engin to read , and than feedback for server broswer . finially route to client .
至於 main 的檔名 , 是呼應設定呼叫器時的指令.