首页 > 代码库 > nunjucks.js模板渲染

nunjucks.js模板渲染

直接用 script 引入文件:

<script src="http://www.mamicode.com/nunjucks.js"></script>

是使用 render 来直接渲染文件,这种方式支持继承(extends)和包含(include)模板。使用之前需要配置文件的路径:

nunjucks.configure(‘views‘, { autoescape: true });
nunjucks.render(‘index.html‘, { foo: ‘bar‘ });

在 node 端,‘views‘ 为相对于当前工作目录 (working directory) 的路径。在浏览器端则为一个相对的 url,最好指定为绝对路径 (如 ‘/views‘)。

项目的目录结构如下:

技术分享

其中:

主页 index.html

<!DOCTYPE html>
<html>

<head>
    <title>nunjucks 应用</title>
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
</head>
<body>
<div class="contain">
    123
</div>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/nunjucks.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>

模板 tem_data.html :

<div class="main">
    <table class="data-show">
        <th class="thead">
            <td class="name">名字</td>
            <td class="area_id">地区编号</td>
            <td class="area_name">地区名称</td>
            <td class="river_name">河流名称</td>
        </th>
         {% for item in data %}
        <tr>
            <td >{{item.name}}</td>
            <td >{{item.area_id}}</td>
            <td >{{item.area_name}}</td>
            <td >{{item.river_name}}</td>
        </tr>
         {% endfor %}
    </table>
</div>

app.js:

  var data=http://www.mamicode.com/[{
extra: { },
time: "2016-09-29T08:00:00",
val: 195,
level_index: 5,
id: "71552116",
name: "日溪乡汶石",
lng: 119.1921,
lat: 26.3158,
type: "PP",
type_name: "雨量站",
subjection: "防汛",
area_id: "350111",
area_name: "晋安区",
river_name: "闽江",
water_system: "闽江",
station_position: 0,
city_code: "350100",
city_name: "福州市"
},
{
extra: { },
time: "2016-09-29T16:00:00",
val: 192,
level_index: 5,
id: "71502056",
name: "寿山乡红寮",
lng: 119.237221,
lat: 26.220278,
type: "ZZ",
type_name: "河道水位站",
subjection: "防汛",
area_id: "350111",
area_name: "晋安区",
river_name: "寿山乡红寮",
water_system: "寿山乡红寮",
station_position: 0,
city_code: "350100",
city_name: "福州市"}];
   
nunjucks.configure(‘http://127.0.0.1:8080/template‘,{autoescape:true});

var html = nunjucks.render(‘tem_data.html‘,{data:data});

//document.getElementsByClassName("contain").innerHTML=html;  //nocan

 $(".contain").append(html);//yes
//console.log(html);

 为了能够成功渲染,需要修改端口:

技术分享

 

nunjucks.js模板渲染