从字符串渲染pug模板?

3

能否使用Pug模板将HTML页面渲染为字符串呢?在Node.js中,您可以像这样使用“Pug模板”生成HTML页面:

var express = require('express')  
var app = express()  
app.set('view engine', 'pug')
var mytemplate="html\n\thead\n\tbody";
app.get('/', function (req, res) {  
    res.render(
        'index',
        { title: 'Hey Hey Hey!', message: 'Yo Yo'})
})

app.listen(3000, function () {  
    console.log('Example app listening on port 3000!')
})

模板文件应该放在./views/index.pug。

可以使用保存在“mytemplate” -变量中的模板,而不是文件内容吗?

1个回答

6
您可以使用 pug.render() 函数来进行操作:
const pug = require('pug');
...
app.get('/', function (req, res) {  
  res.send( pug.render(mytemplate, { title: 'Hey Hey Hey!', message: 'Yo Yo'}) ) );
})

或者,您可以使用pug.compile()预编译模板,这在性能方面会更快一些:

var mytemplate = pug.compile("html\n\thead\n\tbody");

app.get('/', function (req, res) {  
  res.send( mytemplate({ title: 'Hey Hey Hey!', message: 'Yo Yo'}) );
})

顺便问一下:你使用了“const”关键字,与“var”有显著的区别吗? - neoexpert
const 防止变量重新赋值,这种方式更加严格,我认为对于模块引用更好 :) - robertklep
成功了!现在我可以直接在浏览器中开发我的 Web 应用程序。 - neoexpert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接