ejs使用

ejs使用

从npm上下载最新的ejs刚写了个例子 

先pull出来,网上太多例子都不好用,googlecode上的代码根本下不下来,只能去翻npm安装下来的文件里的说明文件,模仿着写出来一个

var ejs = require('..'),
    fs = require('fs'), 
    read = fs.readFileSync;


/**
 * Load fixture `name`.
 */

function fixture(name) {
  return read('' + name, 'utf8').replace(/
/g, '').trim();
}


var data = {title: 'Cleaning Supplies', supplies: ['mop', 'broom', 'duster']};

// var html = ejs.compile('cleaning.ejs', data);

// console.log(html);

var str = fixture('cleaning.ejs');
var template = ejs.compile(str, 'cache');
template(data);
// => Rendered HTML string

var html = ejs.render(str, data, 'cache');
// => Rendered HTML string

console.log(html);

一共两个文件,template文件在同目录下,内容是官网上拿的;

<h1><%= title %></h1>
<ul>
    <% for(var i=0; i<supplies.length; i++) { %>
        <li>
            <a href='supplies/<%= supplies[i] %>'>
                <%= supplies[i] %>
            </a>
        </li>
    <% } %>
</ul>

结果如下:

期待成为寂寞高手的武林老白
原文地址:https://www.cnblogs.com/aquariusm/p/4249553.html