From 341b9dbddbeb1dc9ec9b8b9eacec7b47f8f47833 Mon Sep 17 00:00:00 2001 From: Dennis Schridde Date: Sun, 29 Jan 2017 04:59:19 +0100 Subject: [PATCH] Fix partials to indent as demanded by the mustache spec The mustache specs [1] and testsuite [2], as well as the lustache README.md [3] demand that partials be indented. [1]: http://mustache.github.io/mustache.5.html [2]: https://github.com/mustache/spec/blob/v1.1.3/specs/partials.yml#L82-L100 [3]: https://github.com/Olivine-Labs/lustache#partials --- src/lustache/renderer.lua | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/lustache/renderer.lua b/src/lustache/renderer.lua index bcbc9a1..e87a405 100755 --- a/src/lustache/renderer.lua +++ b/src/lustache/renderer.lua @@ -64,7 +64,7 @@ local function compile_tokens(tokens, originalTemplate) t == "^" and rnd:_inverted( token.value, ctx, subrender(i, token.tokens) ) or - t == ">" and rnd:_partial(token.value, ctx, originalTemplate) or + t == ">" and rnd:_partial(token.value, ctx, originalTemplate, token.startIndex) or (t == "{" or t == "&") and rnd:_name(token.value, ctx, false) or t == "name" and rnd:_name(token.value, ctx, true) or t == "text" and token.value or "" @@ -249,7 +249,7 @@ function renderer:_inverted(name, context, callback) return "" end -function renderer:_partial(name, context, originalTemplate) +function renderer:_partial(name, context, originalTemplate, startIndex) local fn = self.partial_cache[name] -- check if partial cache exists @@ -264,7 +264,23 @@ function renderer:_partial(name, context, originalTemplate) fn = self:compile(partial, nil, originalTemplate) self.partial_cache[name] = fn end - return fn and fn(context, self) or "" + + local startOfLineIndex = 1 + for i = startIndex, 1, -1 do + if string_sub(originalTemplate, i, i) == "\n" then + startOfLineIndex = i + 1 + break + end + end + local indent = string_sub(originalTemplate, startOfLineIndex, startIndex - 1) + + local str = fn and fn(context, self) or "" + local buf = {} + for i,line in ipairs(string_split(str, "\n")) do + buf[#buf+1] = (i > 1 and indent or "") .. line .. "\n" + end + + return table_concat(buf) end function renderer:_name(name, context, escape)