diff --git a/src/main/java/com/samskivert/mustache/Template.java b/src/main/java/com/samskivert/mustache/Template.java
index a006fba..14e142a 100644
--- a/src/main/java/com/samskivert/mustache/Template.java
+++ b/src/main/java/com/samskivert/mustache/Template.java
@@ -20,6 +20,8 @@ import java.util.concurrent.ConcurrentHashMap;
* Given a name {@code foo}, the following mechanisms are supported for resolving its value
* (and are sought in this order):
*
+ * - If the variable has the special name {@code this} the context object itself will be
+ * returned. This is useful when iterating over lists.
*
- If the object is a {@link Map}, {@link Map#get} will be called with the string {@code foo}
* as the key.
*
- A method named {@code foo} in the supplied object (with non-void return value).
@@ -101,6 +103,10 @@ public class Template
protected static VariableFetcher createFetcher (Key key)
{
+ if (key.name == THIS_NAME) {
+ return THIS_FETCHER;
+ }
+
if (Map.class.isAssignableFrom(key.cclass)) {
return MAP_FETCHER;
}
@@ -225,4 +231,12 @@ public class Template
return ((Map,?>)ctx).get(name);
}
};
+
+ protected static final VariableFetcher THIS_FETCHER = new VariableFetcher() {
+ public Object get (Object ctx, String name) throws Exception {
+ return ctx;
+ }
+ };
+
+ protected static final String THIS_NAME = "this".intern();
}
diff --git a/src/test/java/com/samskivert/mustache/MustacheTest.java b/src/test/java/com/samskivert/mustache/MustacheTest.java
index b2258c4..562d665 100644
--- a/src/test/java/com/samskivert/mustache/MustacheTest.java
+++ b/src/test/java/com/samskivert/mustache/MustacheTest.java
@@ -126,6 +126,15 @@ public class MustacheTest
context("bob}bob", "bar")));
}
+ @Test public void testTopLevelThis () {
+ assertEquals("bar", Mustache.compiler().compile("{{this}}").execute("bar"));
+ }
+
+ @Test public void testNestedThis () {
+ assertEquals("barbazbif", Mustache.compiler().compile("{{#things}}{{this}}{{/things}}").
+ execute(context("things", Arrays.asList("bar", "baz", "bif"))));
+ }
+
protected void test (String expected, String template, Object ctx)
{
assertEquals(expected, Mustache.compiler().compile(template).execute(ctx));