kubal5003
kubal5003

Reputation: 7254

Express & res.render passing the template as string

I would like to perform the res.render, but instead of passing the template file as parameter like this:

res.render('index.hbs', { a: 'B' });

I would like to be able to pass the template as a string like that:

let template = '{{ a }}'
res.render(template, { a: 'B' });

The code above is obviously not working since res.render accepts only file path/name. Any ideas about how to achieve this?

Upvotes: 1

Views: 1140

Answers (1)

Ivan Mladenov
Ivan Mladenov

Reputation: 1847

You can render your template first

var handlebars = require('handlebars');

// set up your handlebars template
var source = '{{ a }}';

// compile the template
var template = handlebars.compile(source);

// call template as a function, passing in your data as the context
var outputString = template({ a: 'B' });

and then send the output to the client

res.send(outputString);

Upvotes: 2

Related Questions