Skip to content

Instantly share code, notes, and snippets.

@Haraldson
Created December 9, 2015 12:49
Show Gist options
  • Save Haraldson/d267d8cb7de1636a66db to your computer and use it in GitHub Desktop.
Save Haraldson/d267d8cb7de1636a66db to your computer and use it in GitHub Desktop.
Handlebars ‘in’ block helper

Explanation

Some APIs only return a certain property if it’s supported in that context. This makes using the traditional {{#if}} block helper difficult, even when passing in the little known includeZero=true; the property value might be null, and in some edge cases even undefined.

define('shared/handlebars/helpers/in', ['handlebars'], function(Handlebars)
{
var inHelper = function(attribute, options)
{
if(arguments.length < 1)
throw new Error('Handlerbars Helper “in” needs an “attribute” parameter');
var result = attribute in options.data.root;
return options[result ? 'fn' : 'inverse'](this);
};
Handlebars.registerHelper('in', inHelper);
return inHelper;
});
{{#in 'someAttribute'}}
{{! Render handling for someAttribute here, even if its initial value is falsy }}
{{else}}
{{! Explain why someAttribute isn’t available in this context, or skip this entire else clause }}
{{/in}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment