Add ability for lambda to change the context for fragment execution

This commit is contained in:
robbytx
2014-03-13 19:38:54 -05:00
parent 3fe5e020d8
commit 75609b42df
2 changed files with 35 additions and 3 deletions
@@ -43,12 +43,22 @@ public class Template
/** Executes this template fragment, writing its result to {@code out}. */
public abstract void execute (Writer out);
/** Executes this template fragment and returns is result as a string. */
/** Executes this template fragment with the provided context, writing its result to {@code out}. */
public abstract void execute (Object context, Writer out);
/** Executes this template fragment and returns its result as a string. */
public String execute () {
StringWriter out = new StringWriter();
execute(out);
return out.toString();
}
/** Executes this template fragment with the provided context, and returns its result as a string. */
public String execute (Object context) {
StringWriter out = new StringWriter();
execute(context, out);
return out.toString();
}
}
/**
@@ -93,9 +103,17 @@ public class Template
}
}
protected Fragment createFragment (final Segment[] segs, final Context ctx) {
protected Fragment createFragment (final Segment[] segs, final Context currentCtx) {
return new Fragment() {
@Override public void execute (Writer out) {
@Override public void execute(Writer out) {
execute(currentCtx, out);
}
@Override public void execute(Object context, Writer out) {
execute(currentCtx.nest(context, 0, false, false), out);
}
private void execute(Context ctx, Writer out) {
for (Segment seg : segs) {
seg.execute(Template.this, ctx, out);
}
@@ -664,6 +664,20 @@ public class MustacheTest
}));
}
@Test public void testLambdaWithContext () {
test("a in l1, a in l2", "{{#l1}}{{a}}{{/l1}}, {{#l2}}{{a}}{{/l2}}",
context("l1", new Mustache.Lambda() {
public void execute(Template.Fragment frag, Writer out) throws IOException {
frag.execute(context("a", "a in l1"), out);
}
}, "l2", new Mustache.Lambda() {
public void execute(Template.Fragment frag, Writer out) throws IOException {
frag.execute(context("a", "a in l2"), out);
}
}
));
}
@Test public void testNonStandardDefaultDelims () {
test(Mustache.compiler().withDelims("<% %>"), "bar", "<%foo%>", new Object() {
String foo = "bar";