ScottLee
ScottLee

Reputation: 75

Handlebarsjs left behind expression

I am looking for a solution how to compile HTML template without ignoring unfilled data using Handlebarsjs.

For example:

var Handlebars = require("handlebars");
var html = "<div>{{foo}}</div><div>{{foo2}}</div>";
html = Handlebars.compile(html)({
    foo : "This is a sample"
});
console.log(html);

Is there available compiling option that could help me to left behind the expression? Like that:

html = Handlebars.compile(html)({
   foo : "This is a sample"
},{isLeftBehindEx:true});
<div>This is a sample</div><div>{{foot2}}</div>

Upvotes: 1

Views: 161

Answers (2)

nikoshr
nikoshr

Reputation: 33364

  1. Expressions are helpers

    This expression means "look up the title property in the current context". [...]
    Actually, it means "look for a helper named title, then do the above" [...]

  2. When a helper is missing, an internal helper named helperMissing is called to replace the missing expression

  3. You can pass pass an options hash when you execute your template to provide custom helpers.

Armed with that knowledge, you can for example replace your missing values with an arbitrary string representation:

var compiled = Handlebars.compile(html);
html = compiled({
    foo : "This is a sample"
}, {
    helpers: {
        helperMissing: function(o) {
            return '{{' + o.name + '}}';
        }
    }
});

And a demo http://jsfiddle.net/jrtrvmd4/

Or you can override the helperMissing globally if you prefer and condition its output on an optional flag you pass as a data option, for example isLeftBehindEx as you suggested :

Handlebars.registerHelper('helperMissing', function(o) {
    return (o.data.isLeftBehindEx) ? '{{' + o.name + '}}' : "";
});

html = compiled({
    foo : "This is a sample"
}, {
    data: {
        isLeftBehindEx: true
    }
});

http://jsfiddle.net/jrtrvmd4/3/

Upvotes: 1

ScottLee
ScottLee

Reputation: 75

For reusing the built-in method of Handlebarsjs without redeveloping unncessary code, I still use the following way to achieve my goal...

var Handlebars = require("handlebars");
Handlebars.registerHelper('foo2', function(val, options) {
    return "{{"+val.name+"}}"
});
var html = "<div>{{foo}}</div><div>{{foo2}}</div>";
//compile but stay behind the expressions
console.log(Handlebars.compile(html)({
    foo : "This is a sample"
}));
//compile and remove the expression as usual
Handlebars.unregisterHelper('foo2');
console.log(Handlebars.compile(html)({
    foo : "This is a sample"
}));

Upvotes: 0

Related Questions