Skip to content

Instantly share code, notes, and snippets.

@kevinmarx
Last active December 10, 2015 23:48
Show Gist options
  • Save kevinmarx/4511542 to your computer and use it in GitHub Desktop.
Save kevinmarx/4511542 to your computer and use it in GitHub Desktop.
oneof block helper for handlebars.
var Handlebars = require('handlebars')
// Oneof block helper. Works like an `if` block helper but allows you to evalutate context against a set.
// You can also use this as a part of a "if else" statement.
// The `key` argument is optional, if not set the key is the context.
//
// {{#oneof foo set='bar, baz' key=foo}}{{/oneof}}
//
// {{#oneof foo set='bar, baz' key=foo}}<div/>{{else}}<div/>{{/oneof}}
Handlebars.registerHelper('oneof', function(context, options){
var set = Handlebars.Utils.escapeExpression(options.hash.set).replace(/\s*(,|^|$)\s*/g, "$1").split(',')
var key = options.hash.key || context
var i = 0
var conditional = false
if(typeof context === "function") { context = context.call(this) }
if(set instanceof Array) {
while(i<set.length && conditional == false ) {
if(key === set[i]) {
i++
conditional = true
return options.fn(this)
} else {
i++
}
if(i == set.length && conditional == false) {
return options.inverse(this)
}
}
} else {
if(key === set.toString()){
return options.fn(this)
} else {
return options.inverse(this)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment