ejs是一個node.js樣板引擎,配合express使用會非常方便

ejs source

安裝ejs

1npm install ejs

使用方式
app.js

1//Express
2var express = require("express");
3var http = express();
4var port = 1234;
5 
6// Configuration
7http.configure( function (){
8        //定義view的路徑,view的檔名後面要加上ejs(例如index.ejs)
9        this.set( 'views', __dirname + '/views' );
10        //將jade改成ejs
11        this.set( 'view engine', 'ejs' );
12});
13 
14http.listen(port);
15 
16http.get('/', function(req, res, next){
17        //render index.ejs
18        res.render('index',{
19                title :'Hello',
20                users :['johnson','maple'],
21        });
22});

views/index.ejs

1<!-- include head.ejs -->
2<% include head %>
3 
4<!-- 使用<%-輸出時會做 HTML escape -->
5<h1 id="page-title"><%- title %></h1>
6 
7<ul>
8<!-- foreach  -->
9<% users.forEach(function(user){ %>
10        <li><%= user %></li>
11<% }) %>
12</ul>

其實ejs用起來跟PHP的Smarty很像,如果有用過Smarty的人會很容易上手

Categories: Node.js