Reputation: 4034
In server.js
I have something like this:
var express = require('express');
var path = require('path');
var exphbs = require('express-handlebars');
var app = new express();
var handlebars = require('./helpers.js')(exphbs);
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', handlebars.engine);
app.set('view engine', '.hbs');
app.set ('port', (process.env.PORT || 5000));
app.get('/', function(req,res){
res.render('home', {
title: 'Express App with Handlebars templates',
content: 'This is some content',
persons: [
{
name: 'branchito',
instrument: 'guitar',
},
{
name: 'joe',
instrument: 'flute',
},
]
});
});
app.listen(app.get( 'port' ), function(){
console.log('Server started on port ' + app.get('port'));
})
And then in my helpers.js
file:
function hbsHelpers(hbs) {
return hbs.create({
helpers: { // This was missing
inc: function(value, options) {
console.log('reading it');
return parseInt(value) + 1;
},
strong: function(text) {
return '<strong>' + text + '</strong>';
}
// More helpers...
}
});
}
module.exports = hbsHelpers;
But then the output generated by strong
helper renders that as a <strong>...</strong>
.. How would I go to have that string unescaped, I know there is Handlebars.SafeString()
but don't know how to use it from this express-handlebars instance..
Upvotes: 1
Views: 2439
Reputation: 394
Not sure if I am understanding it right and probably a little bit too late, but I had the same (or at least a similar issue):
When I wanted to show my content with {{ var }} and var was e.g.
<strong>somevar</strong>
I had the problem that it was rendered as
<strong>somevar</strong>
My workaround was that the variable wasn't rendered through the default Handlebars renderer, but creating a function doing it for you:
var hbs = exphbs.create({
/* ... */
helpers: {
raw: function (a) { return a; },
}
});
And in my .handlebars file I did the following:
<p>{{#raw var}}{{/raw}}</p>
So, it's basically the same as you did. I tried your code as well, and it worked for me. Probably you're not calling it right in handlebars file?
Upvotes: 0
Reputation: 14352
To output raw HTML instead of escaped HTML use three curly braces instead of two.
For example:
{{{strong}}}
Will output the raw HTML from the helper:
strong: function(text) {
return '<strong>' + text + '</strong>';
}
Upvotes: 3