From 306feb497c72d539ce0f6f926fc8844fb35844fe Mon Sep 17 00:00:00 2001 From: kpdecker Date: Sun, 9 Feb 2014 17:22:18 -0600 Subject: [PATCH] Implement lookup helper --- lib/handlebars/base.js | 4 ++++ lib/handlebars/compiler/compiler.js | 3 ++- spec/builtins.js | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index 7ebfc5567..02d274d3a 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -193,6 +193,10 @@ function registerDefaultHelpers(instance) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; instance.log(level, context); }); + + instance.registerHelper('lookup', function(obj, field, options) { + return obj && obj[field]; + }); } export var logger = { diff --git a/lib/handlebars/compiler/compiler.js b/lib/handlebars/compiler/compiler.js index cfcc70ac5..21e1024f2 100644 --- a/lib/handlebars/compiler/compiler.js +++ b/lib/handlebars/compiler/compiler.js @@ -85,7 +85,8 @@ Compiler.prototype = { 'if': true, 'unless': true, 'with': true, - 'log': true + 'log': true, + 'lookup': true }; if (knownHelpers) { for (var name in knownHelpers) { diff --git a/spec/builtins.js b/spec/builtins.js index 53f46ccd5..bbe494e08 100644 --- a/spec/builtins.js +++ b/spec/builtins.js @@ -203,4 +203,25 @@ describe('builtin helpers', function() { equals("whee", logArg, "should call log with 'whee'"); }); + + describe('#lookup', function() { + it('should lookup arbitrary content', function() { + var string = '{{#each goodbyes}}{{lookup ../data .}}{{/each}}', + hash = {goodbyes: [0, 1], data: ['foo', 'bar']}; + + var template = CompilerContext.compile(string); + var result = template(hash); + + equal(result, 'foobar'); + }); + it('should not fail on undefined value', function() { + var string = '{{#each goodbyes}}{{lookup ../bar .}}{{/each}}', + hash = {goodbyes: [0, 1], data: ['foo', 'bar']}; + + var template = CompilerContext.compile(string); + var result = template(hash); + + equal(result, ''); + }); + }); });