When nesting for non-list contexts, inherit list info.

This ensures that if you enter a conditional block while inside a list
block, the list "state" from the outer list will still be visible. For
example (somewhat contrived, but gets the point across):

{{#list}}
{{#name}}{{-index}}. {{.}}{{/name}}
{{^name}}{{-index}}. No name!{{/name}}
{{/list}}

Yields something like:

1. Bob
2. Mary
3. No name!
4. Jim

Fixes #90.
This commit is contained in:
Michael Bayne
2017-09-20 09:43:14 -07:00
parent 49720df4ea
commit 172f35fb64
3 changed files with 23 additions and 2 deletions
@@ -878,7 +878,7 @@ public class Mustache
} else if (_comp.isFalsey(value)) {
// omit the section
} else {
executeSegs(tmpl, ctx.nest(value, 0, false, false), out);
executeSegs(tmpl, ctx.nest(value), out);
}
}
@Override public void decompile (Delims delims, StringBuilder into) {
@@ -157,7 +157,7 @@ public class Template
execute(currentCtx, out);
}
@Override public void execute (Object context, Writer out) {
execute(currentCtx.nest(context, 0, false, false), out);
execute(currentCtx.nest(context), out);
}
@Override public Object context () {
return currentCtx.data;
@@ -339,6 +339,10 @@ public class Template
this.onLast = onLast;
}
public Context nest (Object data) {
return new Context(data, this, index, onFirst, onLast);
}
public Context nest (Object data, int index, boolean onFirst, boolean onLast) {
return new Context(data, this, index, onFirst, onLast);
}
@@ -431,6 +431,23 @@ public abstract class SharedTests extends GWTTestCase
context("things", Arrays.asList("foo", "bar", "baz")));
}
@Test public void testNestedIndex () {
class Foo {
public String name;
public Integer quantity;
public Foo(String name, Integer quantity) {
this.name = name;
this.quantity = quantity;
}
}
String tmpl =
"{{#fooList}}\n" +
"{{#quantity}}|q{{-index}}={{quantity}}{{/quantity}}|{{name}}\n" +
"{{/fooList}}";
test("|q1=1|a\n|b\n", tmpl,
context("fooList", Arrays.asList(new Foo("a", 1), new Foo("b", null))));
}
@Test public void testLineReporting () {
String tmpl = "first line\n{{nonexistent}}\nsecond line";
try {