溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

node.js學習之swig

發布時間:2020-07-19 11:22:47 來源:網絡 閱讀:1686 作者:lixiaoyu1223 欄目:web開發

超簡單的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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女