Search code examples
node.jshandlebars.js

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>

Solution

    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/