Skip to content
Permalink
Browse files

added MustacheCustomContext

  • Loading branch information...
devinrsmith committed Aug 21, 2018
1 parent 4533567 commit 433e9677d4fdb8a695c25bbe848647d7b9bcfbd6
@@ -75,6 +75,7 @@ void executeTemplate (Reader template, Writer out, Map<String, String> data) {
The execution context can be any Java object. Variables will be resolved via the following
mechanisms:

* If the context is a `MustacheCustomContext`, `MustacheCustomContext.get` will be used.
* If the context is a `Map`, `Map.get` will be used.
* If a non-void method with the same name as the variable exists, it will be called.
* If a non-void method named (for variable `foo`) `getFoo` exists, it will be called.
@@ -35,6 +35,7 @@
}

public Mustache.VariableFetcher createFetcher (Object ctx, String name) {
if (ctx instanceof MustacheCustomContext) return CUSTOM_FETCHER;
if (ctx instanceof Map<?,?>) return MAP_FETCHER;

// if the name looks like a number, potentially use one of our 'indexing' fetchers
@@ -65,6 +66,17 @@ protected static ArrayHelper arrayHelper (Object ctx) {
return null;
}

protected static final Mustache.VariableFetcher CUSTOM_FETCHER = new Mustache.VariableFetcher() {
public Object get (Object ctx, String name) throws Exception {
MustacheCustomContext custom = (MustacheCustomContext)ctx;
Object val = custom.get(name);
return val == null ? Template.NO_FETCHER_FOUND : val;
}
@Override public String toString () {
return "CUSTOM_FETCHER";
}
};

protected static final Mustache.VariableFetcher MAP_FETCHER = new Mustache.VariableFetcher() {
public Object get (Object ctx, String name) throws Exception {
Map<?,?> map = (Map<?,?>)ctx;
@@ -0,0 +1,8 @@
package com.samskivert.mustache;

/**
* Provides a simple interface for callers to implement their own logic for contextual values.
*/
public interface MustacheCustomContext {
Object get(String name) throws Exception;
}
@@ -45,6 +45,15 @@
});
}

@Test public void testMustacheCustomContext() {
test("bar", "{{foo}}", new MustacheCustomContext() {
@Override
public Object get(String name) {
return "foo".equals(name) ? "bar" : null;
}
});
}

public interface HasDefault {
default String getFoo () { return "bar"; }
}

0 comments on commit 433e967

Please sign in to comment.
You can’t perform that action at this time.