From 209433bfa4acbe855fd747e681ec4340425f1e13 Mon Sep 17 00:00:00 2001 From: fedarovs Date: Thu, 17 Dec 2015 16:16:03 +0300 Subject: [PATCH] adding support for leading dot. see https://github.com/mustache/spec/issues/52 --- lib/template.js | 8 +++----- test/index.js | 7 +++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/template.js b/lib/template.js index 14f396d..39424ee 100644 --- a/lib/template.js +++ b/lib/template.js @@ -127,7 +127,7 @@ var Hogan = {}; pass = !!val; if (!inverted && pass && ctx) { - ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]); + ctx.push(val); } return pass; @@ -137,13 +137,11 @@ var Hogan = {}; d: function(key, ctx, partials, returnFound) { var found, names = key.split('.'), - val = this.f(names[0], ctx, partials, returnFound), + val = names[0] === '' ? ctx[ctx.length - 1] : this.f(names[0], ctx, partials, returnFound), doModelGet = this.options.modelGet, cx = null; - if (key === '.' && isArray(ctx[ctx.length - 2])) { - val = ctx[ctx.length - 1]; - } else { + if (key !== '.') { for (var i = 1; i < names.length; i++) { found = findInScope(names[i], val, doModelGet); if (found !== undefined) { diff --git a/test/index.js b/test/index.js index ec0777e..2d3f5a0 100644 --- a/test/index.js +++ b/test/index.js @@ -684,6 +684,13 @@ test("Dotted Names", function() { is(s, '"Joe" == "Joe"', "dotted names work"); }); +test("Leading Dot", function() { + var text = "{{#items}}{{.title}}{{/items}}"; + var t = Hogan.compile(text); + var s = t.render({items: [{title: 'a'}, {title: 'b'}, {}], title: 'ha'}); + is(s, "ab", "leading dot forces lookup on top context"); +}); + test("Implicit Iterator", function() { var text = '{{#stuff}} {{.}} {{/stuff}}'; var t = Hogan.compile(text);