超簡單的swig用法,都不用多解釋,上代碼:
index.js:
'use strict';
var http = require('http'),
swig = require('swig');
http.createServer(function (req, res) {
var tmpl = swig.compileFile(__dirname + '/index.html'),
renderedHtml = tmpl({
people: [
{ name: 'Paul', age: 28 },
{ name: 'Jane', age: 26 },
{ name: 'Jimmy', age: 45 }
],
title: 'Basic Example'
});
res.writeHead(200, { 'Content-Type': 'text/html' });
console.log(renderedHtml);
res.end(renderedHtml);
}).listen(1337);
console.log('Application Started on http://localhost:1337/');tmpl 應該是swig返回的一個函數,具體是什么沒仔細看,renderedHtml是替換過值的hmtml字符串。
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ title }}</title>
</head>
<body>
<h2>{{ title }}</h2>
<ul>
{% for person in people %}
{% for person in people %}
<li>{{ person.name }} age {{ person.age }}</li>
{% endfor %}
{% endfor %}
</ul>
</body>
</html>html里的變量要和js中的對像中的屬性一一對應,變量用 {{}} (雙花括號)表示,還可以有for循環和if判斷,如果是有這類的關鍵字,要用{% %} 包括,包括中的內容就會根據條件決定顯示或不顯示或顯示多少次。還可以循環嵌套,很容易明白,一看就懂了。
參考 http://www.w3hacker.com/nodejs-swig-example.html
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。