Express開發實例(2) —— Jade模板引擎

前一篇經過helloworld,簡單介紹了Express中的開發,本篇繼續深刻的學習express的模板。css

關於Jade的用法,網上有不少,本篇參考:Jade語法html

安裝相關模塊

在實驗代碼前,應該先安裝express和jade:node

npm install express
npm install jade

簡單介紹本篇使用的api

1 爲了使用jade,先要設置express默認的模板引擎,用法以下:git

app.set('view engine', 'jade');//設置默認的模板引擎

2 若是要進行樣式的定義,就要建立靜態文件目錄,該目錄中的內容,能夠直接在瀏覽器中獲取到:github

app.use(express.static(路徑));

好比路徑爲public,那麼咱們在訪問localhost:3000/pubic/xxxx就能夠獲得相應的文件。express

3 設置視圖的對應目錄npm

app.set('views',xxxx);

4 向特定路徑的視圖返回數據api

res.render('視圖的路徑', { 返回的數據名稱:返回的數據內容});

代碼預覽

建立index.js文件:瀏覽器

var express = require('express');//引入express模塊
var app = express();//建立應用

//定義public路徑
var pub = __dirname + '/public';
app.use(express.static(pub));//設置靜態目錄爲pubic
app.set('views', __dirname + '/views');//設置views路徑映射到views文件夾

app.set('view engine', 'jade');//設置默認的模板引擎

function User(name, email) {
  this.name = name;
  this.email = email;
}

var users = [
    new User('tj', 'tj@vision-media.ca'), 
    new User('ciaran', 'ciaranj@gmail.com'),
    new User('aaron', 'aaron.heckmann+github@gmail.com')
];

app.get('/', function(req, res){
  res.render('users/test', { users: users });
});

app.use(function(err, req, res, next) {
  res.send(err.stack);
});

app.listen(3000);
console.log('Express started on port 3000');

這段代碼首先建立了express的應用實例,而後設置相關的靜態目錄、視圖目錄、模板引擎等等。app

而後建立了幾個user對象,返回給特定的視圖。

建立模板

建立模板index.jade,注意建立的模版中,只能使用空格來進行格式化。不能同時使用製表符和空格。

doctype html
html
  head
  title Jade Example
  link(rel="stylesheet", href="/stylesheets/style.css")

  body
    h1 Users
    #users
    for user in users
      h2= user.name
      .email= user.email

語法參考其餘的Jade語法說明便可。

添加樣式文件

在靜態目錄中,添加樣式文件style.css:

body {
  padding: 50px 80px;
  font: 14px "Helvetica Nueue", "Lucida Grande", Arial, sans-serif;
}
.email{
    color: blue;
}

文件目錄

根目錄myqq
 \------node_modules
    |    \-------express
    |    \-------jade
    |
    \------public
    |    \------stylesheets
    |         \-------style.css
 \------views
    |    \------test
    |          \------index.jade
    index.js

執行node index既可運行樣例。

相關文章
相關標籤/搜索