模板引擎

 

var ejs = require("ejs");
var fs = require("fs");
var http = require("http");


var server = http.createServer(function(req,res){
    fs.readFile("./views/index.ejs",function(err,data){
        //绑定模板
        var template = data.toString();
        var dictionary = {
            a:6,
            news : [
                {"title":"xxxxx","count":10},
                {"title":"哈哈哈哈","count":20},
                {"title":"逗你玩儿的","count":30}
            ]
        };
        /*
        var dictionary = {
          a:6,
          news : ["1期班太牛逼了","高薪就业","哈哈哈哈哈"]
};
        */
        var html = ejs.render(template,dictionary);

        //显示
        res.writeHead(200,{"Content-Type":"text/html;charset=UTF8"});
        res.end(html);
    });
});

server.listen(80,"127.0.0.1");

 

<ul>
        <% for(var i = 0 ; i < news.length ; i++){ %>
            <li><%= news[i] %></li>
        <% } %>
    </ul>

 

建议使用jode.js 模板引擎,类似Python,利用缩进,可以直接生成代码,而不是变成字符串

posted @ 2017-11-02 22:32  Erick-LONG  阅读(140)  评论(0编辑  收藏  举报