Chris
Chris

Reputation: 58192

How to remove template markup if data is missing in Handlebars?

How would one remove all the template markup from a HTML snippet if the data wasn't present.

var $target = $(target);
var dataString = // json from feed ! Sometimes fails

if( typeof dataString !== "undefined") {
    var data = $.parseJSON(dataString);
    var template = Handlebars.compile($target.html());
    var html = template(integrationData);
    $target.html(html);
} else {
    // What goes here?
    // I am making up "stripTags"
    Handlebars.stripTags($target.html());
}

Basically I want to automatically strip out all the {{ and }} as a failsafe.

Upvotes: 0

Views: 750

Answers (1)

Gavin Hellyer
Gavin Hellyer

Reputation: 328

Handlebars will ignore any {{whatever}} if the object does not exist and they will be removed from the markup.

If your feed fails default to an empty object:

var $target = $(target);
var dataString = // json from feed ! Sometimes fails
var data = {};

if( typeof dataString !== "undefined") {
    data = $.parseJSON(dataString);
}

var template = Handlebars.compile($target.html());
var html = template(data);
$target.html(html);

Hope that helps?

Upvotes: 1

Related Questions