Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handlebars relational operators #handlebars #helper #cc

Handlebars relational operators

This is a series of MATLAB style relational operators for Handlebars.

Operators

With any helper a, b are values compared if a condition valudates

  • eq - equal to
  • ne - not equal to
  • lt - less than
  • gt - greater than
  • le - less than or equal to
  • ge - greater than or equal to

Usage

Include the operators needed in your application. Then condition in your template, for example:

{{#eq a b}}This is output if it validates{{/eq}}

Credits

Created by Makis Tracend

// equal
Handlebars.registerHelper('eq', function( a, b ){
var next = arguments[arguments.length-1];
return (a === b) ? next.fn(this) : next.inverse(this);
});
// greater than or equal to
Handlebars.registerHelper('ge', function( a, b ){
var next = arguments[arguments.length-1];
return (a >= b) ? next.fn(this) : next.inverse(this);
});
// greater than
Handlebars.registerHelper('gt', function( a, b ){
var next = arguments[arguments.length-1];
return (a > b) ? next.fn(this) : next.inverse(this);
});
// less than or equal to
Handlebars.registerHelper('le', function( a, b ){
var next = arguments[arguments.length-1];
return (a <= b) ? next.fn(this) : next.inverse(this);
});
// less than
Handlebars.registerHelper('lt', function( a, b ){
var next = arguments[arguments.length-1];
return (a < b) ? next.fn(this) : next.inverse(this);
});
// not equal
Handlebars.registerHelper('ne', function( a, b ){
var next = arguments[arguments.length-1];
return (a !== b) ? next.fn(this) : next.inverse(this);
});
@adamreisnz

This comment has been minimized.

Copy link

@adamreisnz adamreisnz commented Mar 27, 2018

Simplified version for Node.js handlebars:

handlebars.registerHelper('eq', function(a, b) {
  return (a === b);
});
handlebars.registerHelper('gt', function(a, b) {
  return (a > b);
});
handlebars.registerHelper('gte', function(a, b) {
  return (a >= b);
});
handlebars.registerHelper('lt', function(a, b) {
  return (a < b);
});
handlebars.registerHelper('lte', function(a, b) {
  return (a <= b);
});
handlebars.registerHelper('ne', function(a, b) {
  return (a !== b);
});

Usage:

{{#if (gt someArray.length 1)}}
  Multiple items
{{else}}
  One item
{{/if}}
@hughevans

This comment has been minimized.

Copy link

@hughevans hughevans commented Nov 3, 2020

This works fine in Node:

Handlebars.registerHelper("greaterThan", function (a, b) {
  var next = arguments[arguments.length - 1];
  return a > b ? next.fn() : next.inverse();
});
@MigueBlogs

This comment has been minimized.

Copy link

@MigueBlogs MigueBlogs commented Nov 3, 2020

Good code !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment