Support index access on primitive arrays
This commit is contained in:
@@ -43,8 +43,15 @@ public class DefaultCollector extends BasicCollector
|
||||
Mustache.VariableFetcher fetcher = super.createFetcher(ctx, name);
|
||||
if (fetcher != null) return fetcher;
|
||||
|
||||
// first check for a getter which provides the value
|
||||
Class<?> cclass = ctx.getClass();
|
||||
|
||||
// try generic 'indexing' fetcher for primitive arrays
|
||||
char c = name.charAt(0);
|
||||
if (c >= '0' && c <= '9') {
|
||||
if (cclass.isArray()) return GENERIC_ARRAY_FETCHER;
|
||||
}
|
||||
|
||||
// first check for a getter which provides the value
|
||||
final Method m = getMethod(cclass, name);
|
||||
if (m != null) {
|
||||
return new Mustache.VariableFetcher() {
|
||||
@@ -162,4 +169,16 @@ public class DefaultCollector extends BasicCollector
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected static final Mustache.VariableFetcher GENERIC_ARRAY_FETCHER = new Mustache.VariableFetcher() {
|
||||
public Object get (Object ctx, String name) throws Exception {
|
||||
try {
|
||||
return Array.get(ctx, Integer.parseInt(name));
|
||||
} catch (NumberFormatException nfe) {
|
||||
return Template.NO_FETCHER_FOUND;
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
return Template.NO_FETCHER_FOUND;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,6 +89,19 @@ public class MustacheTest
|
||||
});
|
||||
}
|
||||
|
||||
@Test public void testPrimitiveArrayIndexVariable () {
|
||||
test("1", "{{foo.0}}", new Object() {
|
||||
int[] getFoo () { return new int[] { 1, 2, 3, 4 }; }
|
||||
});
|
||||
}
|
||||
|
||||
@Test public void testPrimitiveArrayIndexOutOfBoundsVariable () {
|
||||
Mustache.Compiler comp = Mustache.compiler().defaultValue("?");
|
||||
test(comp, "?", "{{foo.4}}", new Object() {
|
||||
int[] getFoo () { return new int[] { 1, 2, 3, 4 }; }
|
||||
});
|
||||
}
|
||||
|
||||
@Test public void testCallSiteReuse () {
|
||||
Template tmpl = Mustache.compiler().compile("{{foo}}");
|
||||
Object ctx = new Object() {
|
||||
|
||||
Reference in New Issue
Block a user