Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render pug template from string?

Is it posible to render a html-page with pug template as a string? In nodejs you can generate a html- page with a "pug tempalte" like here:

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!')
})

the template file should be in ./views/index.pug.

is it posible to use the template saved in "mytemplate" -variable instead of the file content?

like image 204
neoexpert Avatar asked Sep 10 '25 19:09

neoexpert


1 Answers

You can use pug.render():

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

Or you can pre-compile your template using pug.compile(), which would be a bit faster, performance-wise:

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

app.get('/', function (req, res) {  
  res.send( mytemplate({ title: 'Hey Hey Hey!', message: 'Yo Yo'}) );
})
like image 123
robertklep Avatar answered Sep 13 '25 10:09

robertklep