From 0bef6a06e59b1877ccfca8343218ea82fea6d767 Mon Sep 17 00:00:00 2001 From: Michael Bayne Date: Thu, 21 Oct 2010 23:06:15 +0000 Subject: [PATCH] Added support for composite keys, e.g. foo.bar.baz, which extracts foo from the context, then extracts bar from that object, then extracts baz from that. --- src/main/java/com/samskivert/mustache/Template.java | 9 +++++++++ .../java/com/samskivert/mustache/MustacheTest.java | 12 ++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/main/java/com/samskivert/mustache/Template.java b/src/main/java/com/samskivert/mustache/Template.java index 14e142a..649fc55 100644 --- a/src/main/java/com/samskivert/mustache/Template.java +++ b/src/main/java/com/samskivert/mustache/Template.java @@ -75,6 +75,15 @@ public class Template throw new NullPointerException("Null context for variable '" + name + "'"); } + // if we're dealing with a composite key, resolve each component and use the result to + // resolve the subsequent component and so forth + if (name.indexOf(".") != -1) { + for (String comp : name.split("\\.")) { + ctx = getValue(ctx, comp); + } + return ctx; + } + Key key = new Key(ctx.getClass(), name); VariableFetcher fetcher = _fcache.get(key); if (fetcher != null) { diff --git a/src/test/java/com/samskivert/mustache/MustacheTest.java b/src/test/java/com/samskivert/mustache/MustacheTest.java index 562d665..0443c28 100644 --- a/src/test/java/com/samskivert/mustache/MustacheTest.java +++ b/src/test/java/com/samskivert/mustache/MustacheTest.java @@ -135,6 +135,18 @@ public class MustacheTest execute(context("things", Arrays.asList("bar", "baz", "bif")))); } + @Test public void testStructuredVariable () { + test("hello", "{{foo.bar.baz}}", new Object() { + Object foo () { + return new Object() { + Object bar = new Object() { + String baz = "hello"; + }; + }; + } + }); + } + protected void test (String expected, String template, Object ctx) { assertEquals(expected, Mustache.compiler().compile(template).execute(ctx));