Foreword:
If all front-end pages need to be assembled into HTML strings and then printed to the front desk, it will undoubtedly be a huge workload for developers. Therefore, it is necessary to use front-end templates to focus on The focus is on front-end data, similar to web dynamic languages such as PHP and JSP.
Template selection:
Since it is a team collaboration, in order to reduce the learning cost, I chose EJS, which is similar to the development of PHP and JSP. People who are familiar with this will greatly improve efficiency.
启动webapp 页面 [javascript] view plain copy var express = require("express"); var http = require("http"); var app = express(); ////////////////////// 设置模板 ///////////////////////////// var ejs = require("ejs"); //使用set方法,为系统变量“views”和“view engine”指定值。 app.set("views", __dirname + "/views"); // 指定模板文件的后缀名为html app.set('view engine', 'html'); // 运行hbs模块 app.engine('html', ejs.__express); ////////////////////// 利用文件来拆分路由的规模 ///////////////////////////// var router = express.Router(); var router1 = require('./routes/router1'); var router2 = require('./routes/router2'); var router3 = require('./routes/router3'); var testRouter = require('./routes/test/test'); //设置web工程的根目录 app.use(express.static(__dirname + '/')); app.use('/router1', router1); app.use('/router2', router2); app.use('/router3', router3); app.use('/test', testRouter); http.createServer(app).listen(3000); 控制器routes/router1.js [javascript] view plain copy var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/a', function(req, res, next) { res.render('router1/index', { name: 'Express 路由1' }); }); module.exports = router; 模板页面views/router1/index.html [html] view plain copy <!DOCTYPE html> <html lang="zh-CN"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="../../public/js/jquery.min.js"></script> <script src="../../public/js/hb_common.js"></script> <link rel="stylesheet" href="../../public/css/bootstrap.min.css"> <link rel="stylesheet" href="../../public/css/hb_wap.css"> <title>黄彪测试nodejs模板</title> </head> <body > <button class="btn btn-primary" id="btn"> <%= name %>_post</button> </body> </html>
The above is the detailed content of Share an example code of nodejs ejs front-end template. For more information, please follow other related articles on the PHP Chinese website!