Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
compare block helper for handlebars
// {{compare unicorns ponies operator="<"}}
// I knew it, unicorns are just low-quality ponies!
// {{/compare}}
//
// (defaults to == if operator omitted)
//
// {{equal unicorns ponies }}
// That's amazing, unicorns are actually undercover ponies
// {{/equal}}
// (from http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/)
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
var operator = options.hash.operator || "==";
var operators = {
'==': function(l,r) { return l == r; },
'===': function(l,r) { return l === r; },
'!=': function(l,r) { return l != r; },
'<': function(l,r) { return l < r; },
'>': function(l,r) { return l > r; },
'<=': function(l,r) { return l <= r; },
'>=': function(l,r) { return l >= r; },
'typeof': function(l,r) { return typeof l == r; }
}
if (!operators[operator])
throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);
var result = operators[operator](lvalue,rvalue);
if( result ) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
@lmignot

This comment has been minimized.

Copy link

lmignot commented Jul 8, 2014

Hi, fantastic gist! Thought I'd mention a missing var declaration on line 17: operator = options.hash.operator || "=="; should be: var operator = options.hash.operator || "==";

@Axxon

This comment has been minimized.

Copy link

Axxon commented Jul 23, 2014

Hello thanks for this, just a little mistake on example >
// {{compare unicorns ponies operator="<"}}
is
// {{#compare ...

@broncha

This comment has been minimized.

Copy link

broncha commented Aug 28, 2014

This is a very useful piece of code. However, for me the params I passed were not being evaluated. So I had to add these lines at the beginning of the helper.

lvalue = Ember.Handlebars.get(this, lvalue) || lvalue;
rvalue = Ember.Handlebars.get(this, rvalue) || rvalue;
@augurone

This comment has been minimized.

@alexandrursu

This comment has been minimized.

Copy link

alexandrursu commented Jun 12, 2015

Thanks!

@tarponjargon

This comment has been minimized.

Copy link

tarponjargon commented Dec 27, 2016

Super helpful!

@azeredogab

This comment has been minimized.

Copy link

azeredogab commented Aug 17, 2017

Cool! Thanks Bro!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.