From 222002a64f9ab859bda5a6cf50fa146b48bc5d03 Mon Sep 17 00:00:00 2001 From: Dennis Schridde Date: Sat, 28 Jan 2017 21:40:41 +0100 Subject: [PATCH] Support explicit conditional blocks Explicit conditional blocks are e.g. necessary to support introducing the expansion of a list with an optional header, like in the following example: ```mustache {{?products}} Product names: {{#products}} - {{name}} {{/products}} {{/products}} {{^products}} No products {{/products}} ``` I did not include tests, because their data is included in the corresponding pull request to the Mustache spec. See-Also: https://github.com/mustache/spec/pull/22 See-Also: https://github.com/mustache/spec/issues/55#issuecomment-9936333 --- src/lustache/renderer.lua | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/lustache/renderer.lua b/src/lustache/renderer.lua index bcbc9a1..58e248f 100755 --- a/src/lustache/renderer.lua +++ b/src/lustache/renderer.lua @@ -12,7 +12,7 @@ local patterns = { nonSpace = "%S", eq = "%s*=", curly = "%s*}", - tag = "[#\\^/>{&=!]" + tag = "[#\\^/>{&=!?]" } local html_escape_characters = { @@ -58,6 +58,9 @@ local function compile_tokens(tokens, originalTemplate) for i, token in ipairs(tokens) do local t = token.type buf[#buf+1] = + t == "?" and rnd:_conditional( + token, ctx, subrender(i, token.tokens) + ) or t == "#" and rnd:_section( token, ctx, subrender(i, token.tokens), originalTemplate ) or @@ -89,7 +92,7 @@ local function nest_tokens(tokens) local token, section for i,token in ipairs(tokens) do - if token.type == "#" or token.type == "^" then + if token.type == "?" or token.type == "#" or token.type == "^" then token.tokens = {} sections[#sections+1] = token collector[#collector+1] = token @@ -203,6 +206,16 @@ function renderer:render(template, view, partials) return fn(view) end +function renderer:_conditional(token, context, callback) + local value = context:lookup(token.value) + + if value then + return callback(context, self) + end + + return "" +end + function renderer:_section(token, context, callback, originalTemplate) local value = context:lookup(token.value)