- 快速入门
- 指南
- 参考手册
- 高级主题
- 资源
- Express 词汇表
- Express 社区
- 模板引擎
- Express 中间件
- Express body-parser middleware
- Express compression middleware
- Express connect-rid middleware
- Express cookie-parser middleware
- Express cookie-session middleware
- Express cors middleware
- Express csurf middleware
- Express errorhandler middleware
- Express method-override middleware
- Express morgan middleware
- Express multer middleware
- Express response-time middleware
- Express serve-favicon middleware
- Express serve-index middleware
- Express serve-static middleware
- Express session middleware
- Express timeout middleware
- Express vhost middleware
- Express 实用模板
- 推荐框架
- 推荐书籍和博客
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
模板引擎
Use the app.engine(ext, callback)
method to create your own template engine. ext
refers to the file extension, and callback
is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.
The following code is an example of implementing a very simple template engine for rendering .ntl
files.
var fs = require('fs') // this engine requires the fs module
app.engine('ntl', function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
if (err) return callback(err)
// this is an extremely simple template engine
var rendered = content.toString()
.replace('#title#', '<title>' + options.title + '</title>')
.replace('#message#', '<h1>' + options.message + '</h1>')
return callback(null, rendered)
})
})
app.set('views', './views') // specify the views directory
app.set('view engine', 'ntl') // register the template engine
Your app will now be able to render .ntl
files. Create a file named index.ntl
in the views
directory with the following content.
#title#
#message#
Then, create the following route in your app.
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
When you make a request to the home page, index.ntl
will be rendered as HTML.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论