npm install --save art-template npm install --save express-art-template
咱們在使用時可能在文件中只引用express-art-template,可是咱們也須要安裝art-template,由於express-art-template須要依賴art-templatehtml
在node文件內node
var express = require('express'); var app = express(); // view engine setup,這是關鍵的代碼,第一個參數表示將使用模板引擎文件的後綴名,能夠將art改成html,使用模板引擎的文件的後綴名也就須要是html app.engine('art', require('express-art-template')); //模板引擎的選項 app.set('view options', { debug: process.env.NODE_ENV !== 'production' }); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'art'); // routes app.get('/', function (req, res) { res.render('index.art', { //模板數據以下 user: { name: 'aui', tags: ['art', 'template', 'nodejs'] } }); });
render("文件名",{模板數據});
注意:第一個參數不能寫路徑,通常會默認去項目中的views文件夾下去找文件,這是Express的約定express
app.engine('art', require('express-art-template'));
這是關鍵的代碼,第一個參數表示將使用模板引擎文件的後綴名,能夠將art改成html,使用模板引擎的文件的後綴名也就須要是html。咱們使用art後綴的緣由是爲了是文件能夠一眼看出它使用了模板引擎。npm
若是想要修改默認路徑,不想要viewsjson
app.set('views', path.join(__dirname, 'views'));
修改上面路徑爲你想要的文件夾路徑,可是不要修改第一個參數views。app
app.get('/admin',function(req,res){ res.render('admin/page.html',{ //模板數據以下 title:"系統" }); });
在index.html內ui
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> 這是{{name}}的頁面 </body> </html>
"articles":[ {"id":1,"title":"test1","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":2,"title":"test2","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":3,"title":"test3","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":4,"title":"test4","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":5,"title":"test5","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":6,"title":"test6","author":"ellenxx","date":"2019-1-1","content":"xxx"}, {"id":7,"title":"test7","author":"ellenxx","date":"2019-1-1","content":"xxx"} ]
nodedebug
router.get('/',function(req,res){ fs.readFile('./db.json','utf8',function(err,data){ if(err){ return res.status(500).send('Server err'); } res.render('index.html',{ fruits:["香蕉","蘋果","橘子"], articles: typeof data=='string'?JSON.parse(data).articles:data.articles }); })
htmlcode
<table class="table table-striped"> <thead> <tr> <th>#</th> <th>ID</th> <th>標題</th> <th>日期</th> <th>做者</th> </tr> </thead> <tbody> {{each articles}} <tr> <th>#</th> <td>{{$value.id}}</td> <td>{{$value.title}}</td> <td>{{$value.date}}</td> <td>{{$value.author}}</td> </tr>{{/each}} </tbody> </table>