首页 > 代码库 > Nodejs + express + ejs

Nodejs + express + ejs

特性

  • <% %> 用于控制流

  • <%= %> 用于转义的输出 (会对数据字符进行转义)

    // 数据源
    // 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}]

     

  • <%- %> 用于非转义的输出  (数据原本是什么就输出什么)

  • -%> 结束标签用于换行移除模式

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

 

添加外部js

  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>

 

Nodejs + express + ejs