1. 程式人生 > >ejs渲染頁面

ejs渲染頁面

目錄

介紹

官網地址
ejs下載地址,注意下載ejs.min.js檔案。

作用

渲染頁面。

示例

下載完成之後,直接在靜態html檔案當中引入這個js檔案,這樣就可以使用了。

<script src="ejs.min.js"></script>
<script src="ejs.min.js"></script>
<div id=
"box"></div> <script type="text/javascript"> var people = ['geddy', 'neil', 'alex'], html = ejs.render('<%= people.join(", "); %>', {people: people}); var box = document.getElementById("box"); box.innerHTML = html; </script>

瀏覽器開啟顯示:geddy, neil, alex

兩種渲染方式

1. 方式一:

這種方式把渲染的內容得用引號包裹起來,不太靈活。

<div id="container"></div>
var container = document.getElementById("container");
var arr = [
{"name":"《山居筆記》","author":"餘秋雨","press":"北京師範大學出版社"},
{"name":"《文化苦旅》","author":"餘秋雨","press":"香港中文大學出版社"},
{"name":"《借我一生》","author":"餘秋雨","press":"明報出版社"},
{"name":
"《摩挲大地》","author":"餘秋雨","press":"人民日報出版社"}, ]; var text = ejs.render("" + "<% for(var i = 0;i<arr.length;i++){%>" + "<div>"+ "<span><%= arr[i].name%></span>&nbsp;&nbsp;&nbsp;"+ "<span><%= arr[i].author%></span>&nbsp;&nbsp;&nbsp;"+ "<span><%= arr[i].press%></span>&nbsp;&nbsp;&nbsp;"+ "</div>"+ "<%}%>",{arr:arr}); container.innerHTML = text;

實現效果

2. 方式二:

<div id="container"></div>//html內容
//渲染的模版
<script type="text/template" id="template">
    <div>
        <% for(var i = 0;i<arr.length;i++){ %>
        <span><%= arr[i].name%></span>&nbsp;&nbsp;&nbsp;
        <span><%= arr[i].author%></span>&nbsp;&nbsp;&nbsp;
        <span><%= arr[i].press%></span>&nbsp;&nbsp;&nbsp;
        <br/>
        <% } %>
    </div>
</script>
<script type="text/javascript">
	var container = document.getElementById("container");
	//獲取上面id為template的script渲染模版中的內容
	var template = document.getElementById("template");
var arr = [
{"name":"《山居筆記》","author":"餘秋雨","press":"北京師範大學出版社"},
{"name":"《文化苦旅》","author":"餘秋雨","press":"香港中文大學出版社"},
{"name":"《借我一生》","author":"餘秋雨","press":"明報出版社"},
{"name":"《摩挲大地》","author":"餘秋雨","press":"人民日報出版社"},
];
	var text =template.innerHTML;
	var html = ejs.render(text, {"arr":arr});//渲染資料
	container.innerHTML = html;//新增到container的div元素中
<script>

實現效果和上面圖片一樣。