Nodejs + express + ejs

特性

  • <% %> 用於控制流node

  • <%= %> 用於轉義的輸出 (會對數據字符進行轉義)express

    // 數據源
    // app.js
    
    var tem={
        title:"我是中間部分",
        info:[{Name:"davi", Time:1497591600000},{name:"bill", Time:1497591600000},{name:"can", Time:1497591600000}]
    };
    
    // index.ejs
    //  '<%=JSON.stringify(info)%>'
    [{&#34;Name&#34;:&#34;davi&#34;,&#34;Time&#34;:1497591600000},{&#34;name&#34;:&#34;bill&#34;,&#34;Time&#34;:1497591600000},{&#34;name&#34;:&#34;can&#34;,&#34;Time&#34;:1497591600000},{&#34;name&#34;:&#34;can&#34;,&#34;Time&#34;:1497592600000}]

     

  • <%- %> 用於非轉義的輸出  (數據本來是什麼就輸出什麼)app

  • -%> 結束標籤用於換行移除模式ui

  • 帶有 <%_ _%> 的控制流使用空白字符移除模式spa

 

添加外部jscode

  ejs模板中未能直接使用外掛js 方法, 但可以經過nodejs中 app.js 引入,掛載到 全局變量locals中,ejs中直接調用,直接上代碼:中間件

// common.js

var Common = {    
           timeToDate: function(ts) {
        var Y, M, D, h, m, s;
        var date = new Date(ts);
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
        s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
        return (Y + M + D + h + m + s);
    }
};
module.exports = Common;
// nodejs  app.js

var http=require("http");
var express=require("express");
var fs = require("fs");
var bodyParser = require('body-parser');
var Common = require("./publice/common");
var app=express();

var tem={
    title:"我是中間部分",
    info:[{Name:"davi", Time:1497591600000},{name:"bill", Time:1497591600000},{name:"can", Time:1497591600000}]
};

//掛載靜態資源處理中間件
//app.locals.Common = Common;
app.use(function(req, res, next){
    res.locals.Common = Common;
    next();
});

............................
// index.ejs

<div>
 <%info.forEach(function (name) { %>
                    <dl class="clear-fix">
                        <dd class="wd150"><%= Common.timeToDate(name.Time)%></dd>
                        <dd class="wd120 alc">50天</dd>
                        <dd class="wd120 alc">¥100</dd>                       
                    </dl>
                    <%})%>
</div>
相關文章
相關標籤/搜索