Node操作ejs

Node操作ejs

下載安裝

cnpm i ejs --save
√ Installed 1 packages
√ Linked 0 latest versions
√ Run 0 scripts
√ All packages installed (1 packages installed from npm registry, used 237ms(network 234ms), speed 17.99kB/s, json 1(4.21kB), tarball 0B)

列表和字符串

index.ejs

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<h2>這是ejs</h2>
<h2><%=msg%></h2>
<ul>
    <% for (let i=0; i<list.length; i++) {%>
    <li><%=list[i]%></li>
    <%}%>
</ul>
</body>
</html>

node.js

const ejs = require('ejs');
const http = require('http');
const url = require('url');

http.createServer(function (req, res) {
    res.writeHead(200, {"Content-Type":"text/html;charset='uft-8'"});
    let pathname = url.parse(req.url).pathname;
    let data = '後臺數據';
    let list = [
        '1111',
        '2222',
        '33333'
    ];

    if (pathname === '/index') {
        ejs.renderFile('./index.ejs', {
            msg : data,
            list : list
        }, function (err, data) {
            res.end(data);
        })
    }
}).listen(3000);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章