【问题标题】:Render pug template from string?从字符串渲染哈巴狗模板?
【发布时间】:2017-11-27 19:58:39
【问题描述】:

是否可以将带有 pug 模板的 html 页面呈现为字符串? 在 nodejs 中,您可以生成一个带有“pug tempalte”的 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”变量中保存的模板代替文件内容?

【问题讨论】:

    标签: node.js string templates express pug


    【解决方案1】:

    你可以使用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”有显着区别吗?
    • @AlexanderTyuryaev const 防止重新分配变量,这种方式更加严格,我发现它更适合模块引用:)
    • 有效!现在我可以直接在浏览器中开发我的网络应用程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多