art-template 是一个简约、超快的模板引擎。
它采用作用域预声明的技术来优化模板渲染速度,从而获得接近 JavaScript 极限的运行性能,并且同时支持 NodeJS 和浏览器。
http://aui.github.io/art-template/zh-cn/docs
npm install art-template --save npm install express-art-template --save //或者 yarn add art-template yarn add express-art-template
使用Express应用生成器初始化项目,或者参考一下入门【node.js+express入门】
目录结构大致如下:
修改app.js一下,设置监听端口app.listen
,设置模板引擎为art-template
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.engine('html',require('express-art-template')); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); //监听80端口 app.listen(80,function () { console.log("启动成功, http://localhost/") }) module.exports = app;
新增一个intex.html页面,插入变量
<!DOCTYPE html> <html> <head> <title>{{title}}</title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>{{title}}</h1> <p>Welcome to {{blog}}</p> </body> </html>
使用模板引擎渲染页面已经传递变量
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'node.js+art-template',blog: 'zhengkai.blog.csdn.net' }); }); module.exports = router;
效果预览