I want to check if my current element is active
{{each}}
<div class="num">{{#isActive this}} show this {{/isActive}}</div>
{{/each}}
I created this handlebars template
Handlebars.registerHelper('isActive', function(element, options){
if($(element).hasClass('active')){
return options.fn(this);
}
return options.inverse(this);
});
What did I do wrong?
Handlebars is a string-based templater, which means it works with and outputs strings only. Handlebars doesn't know anything about your environment (which is DOM in the case). So,
this
in template is just a current context object (template's data), not a DOM node.You can't doing any kinds of DOM checks in the template or helper. In Handlebars such checks should be context-based, which means you should pass already prepared data to your template and then simply use
#if
statement:The good practice when using Handlebars or other logic-less templates is to storing current template's state somewhere and work only with it. You get DOM event => update state => re-render template, you get data changed (by AJAX for example) => update state => re-render template, and so on.
State could be a Model in the MVC terminology, or be such a separate entity, it doesn't matter. The key idea is to keeping state out of the template itself and manipulate it only in application. It's core concept of logic-less approach, IMO.
By the way, there is Handlebars fork called HTMLBars, which works with DOMFragments instead of strings. Take a look, maybe it's what you'll be happy with.