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 6d9fa0ba4..bbe494e08 100644 --- a/spec/builtins.js +++ b/spec/builtins.js @@ -1,4 +1,4 @@ -/*global CompilerContext, shouldCompileTo, compileWithPartials */ +/*global CompilerContext, shouldCompileTo, compileWithPartials, handlebarsEnv */ describe('builtin helpers', function() { describe('#if', function() { it("if", function() { @@ -189,16 +189,39 @@ describe('builtin helpers', function() { }); it("#log", function() { - var string = "{{log blah}}"; var hash = { blah: "whee" }; var levelArg, logArg; - handlebarsEnv.log = function(level, arg){ levelArg = level, logArg = arg; }; + handlebarsEnv.log = function(level, arg){ + levelArg = level; + logArg = arg; + }; shouldCompileTo(string, hash, "", "log should not display"); equals(1, levelArg, "should call log with 1"); 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, ''); + }); + }); });