美文网首页
Nodejs(Express) - 06 模板引擎

Nodejs(Express) - 06 模板引擎

作者: Lisa_Guo | 来源:发表于2019-11-22 10:07 被阅读0次

模板用来存放视图元素,目前常用的引擎有Pug,'Jade','Handlebars','Ejs'等,默认为'Jade'
使用模板时需进行setting配置

app.set('views', './views') # 设置模板目录
app.set('view engine', 'pug') # 设置引擎

创建pug模板文件index.pug

html
  head
    title= title
  body
    h1= message

用实际数据填充后返回html

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

app.engine(ext, callback)可定义一个模板引擎。 ext为模板文件扩展名,callback(filepath, options, callback)为吹模板的引擎函数

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

相关文章

网友评论

      本文标题:Nodejs(Express) - 06 模板引擎

      本文链接:https://www.haomeiwen.com/subject/qudfwctx.html