Search code examples
expresshandlebars.jsexpress-handlebars

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?


Solution

  • 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);