Skip to content

Commit

Permalink
Support explicit conditional blocks
Browse files Browse the repository at this point in the history
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: mustache/spec#22
See-Also: mustache/spec#55 (comment)
  • Loading branch information
Dennis Schridde committed Feb 1, 2017
1 parent d63d040 commit 526cfe3
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/lustache/renderer.lua
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ local patterns = {
nonSpace = "%S",
eq = "%s*=",
curly = "%s*}",
tag = "[#\\^/>{&=!]"
tag = "[#\\^/>{&=!?]"
}

local html_escape_characters = {
Expand All @@ -27,6 +27,7 @@ local html_escape_characters = {
local block_tags = {
["#"] = true,
["^"] = true,
["?"] = true,
}

local function is_array(array)
Expand Down Expand Up @@ -63,6 +64,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
Expand Down Expand Up @@ -208,6 +212,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)

Expand Down

0 comments on commit 526cfe3

Please sign in to comment.