Add Fragment.executeTemplate().
Allows a lambda to execute a template in the lambda's own context. This enables 'late bound' template inclusion where the lambda can select a template based on dynamic data in the context at the time it is executed. Closes #92.
This commit is contained in:
@@ -47,6 +47,13 @@ public class Template
|
||||
* provided context will be nested in the fragment's bound context. */
|
||||
public abstract void execute (Object context, Writer out);
|
||||
|
||||
/** Executes {@code tmpl} using this fragment's bound context. This allows a lambda to
|
||||
* resolve its fragment to a dynamically loaded template and then run that template with
|
||||
* the same context as the lamda, allowing a lambda to act as a 'late bound' included
|
||||
* template, i.e. you can decide which template to include based on information in the
|
||||
* context. */
|
||||
public abstract void executeTemplate (Template tmpl, Writer out);
|
||||
|
||||
/** Executes this fragment and returns its result as a string. */
|
||||
public String execute () {
|
||||
StringWriter out = new StringWriter();
|
||||
@@ -159,6 +166,9 @@ public class Template
|
||||
@Override public void execute (Object context, Writer out) {
|
||||
execute(currentCtx.nest(context), out);
|
||||
}
|
||||
@Override public void executeTemplate (Template tmpl, Writer out) {
|
||||
tmpl.executeSegs(currentCtx, out);
|
||||
}
|
||||
@Override public Object context () {
|
||||
return currentCtx.data;
|
||||
}
|
||||
|
||||
@@ -649,6 +649,26 @@ public abstract class SharedTests extends GWTTestCase
|
||||
}));
|
||||
}
|
||||
|
||||
@Test public void testLambdaFragExecTemplate () {
|
||||
Template a = Mustache.compiler().compile("{{value}} should be A");
|
||||
Template b = Mustache.compiler().compile("{{value}} should be B");
|
||||
Mustache.Lambda lambda = new Mustache.Lambda() {
|
||||
public void execute (Template.Fragment frag, Writer out) {
|
||||
String which = frag.execute();
|
||||
if (which.equals("A")) {
|
||||
frag.executeTemplate(a, out);
|
||||
} else if (which.equals("B")) {
|
||||
frag.executeTemplate(b, out);
|
||||
} else {
|
||||
throw new AssertionError("Invalid fragment content: " + which);
|
||||
}
|
||||
}
|
||||
};
|
||||
String tmpl = "[{{#lam}}{{value}}{{/lam}}]";
|
||||
test("[A should be A]", tmpl, context("lam", lambda, "value", "A"));
|
||||
test("[B should be B]", tmpl, context("lam", lambda, "value", "B"));
|
||||
}
|
||||
|
||||
@Test public void testNonStandardDefaultDelims () {
|
||||
test(Mustache.compiler().withDelims("<% %>"), "bar", "<%foo%>", context("foo", "bar"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user