Skip to content

Instantly share code, notes, and snippets.

@servel333
Created February 15, 2018 15:39
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save servel333/21e1eedbd70db5a7cfff327526c72bc5 to your computer and use it in GitHub Desktop.
Save servel333/21e1eedbd70db5a7cfff327526c72bc5 to your computer and use it in GitHub Desktop.
Handlebars {{#if (op ... )}} operators

 Based on https://stackoverflow.com/a/31632215/761771

const reduceOp = function(args, reducer){
  args = Array.from(args);
  args.pop(); // => options
  var first = args.shift();
  return args.reduce(reducer, first);
};

handlebars.registerHelper({
  eq  : function(){ return reduceOp(arguments, (a,b) => a === b); },
  ne  : function(){ return reduceOp(arguments, (a,b) => a !== b); },
  lt  : function(){ return reduceOp(arguments, (a,b) => a  <  b); },
  gt  : function(){ return reduceOp(arguments, (a,b) => a  >  b); },
  lte : function(){ return reduceOp(arguments, (a,b) => a  <= b); },
  gte : function(){ return reduceOp(arguments, (a,b) => a  >= b); },
  and : function(){ return reduceOp(arguments, (a,b) => a  && b); },
  or  : function(){ return reduceOp(arguments, (a,b) => a  || b); },
}); 

Example

{{#if (or 
        (eq section1 "foo")
        (ne section2 "bar"))}}
.. content
{{/if}}

{{#if (or condA condB condC)}}
.. content
{{/if}}
@joaomorais
Copy link

Worked like charm. Thx!

@petervdpas
Copy link

Awesome!

@cskiwi
Copy link

cskiwi commented Sep 5, 2021

Thank you!

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