node.js中ejs模板的使用方式

Embedded JavaScript templates

后台模板引擎

var ejs = require("ejs");

//模板
var string = "哈哈哈哈哈第<%= a %>个";
//数据
var data = {
    a : 6
};
//数据绑定
var html = ejs.render(string, data);
//输出模板数据
console.log(html);

使用在html也页中:




    
    Title


    

哈哈哈第<%= a %>个

    <% for(var i = 0; i < news.length; i++){ %>
  • <%= news[i] %>
  • <%}%>
var ejs = require("ejs");
var fs = require("fs");
var http = require("http");

http.createServer(function (req, res) {
    fs.readFile("./views/index.ejs", function (err, data) {
        var template = data.toString();
        var dictionary = {
            a : 6,
            news : ["行吧", "说的", "很牛逼"]
        };
        var html = ejs.render(template, dictionary);

        res.writeHead(200, {'content-type': 'text/html; charset=utf-8'});
        res.end(html);
    });
}).listen(81, "127.0.0.1");
效果图:

node.js中ejs模板的使用方式_第1张图片

你可能感兴趣的:(前端-node.js)