Added compiler option to provide defaults for missing values

Call missingVariableValue(value) on a Compiler object to get a new
version that will insert "value" for missing values (rather than
throwing an exception).  Useful when you have templates you would
rather generated *something* instead of erroring or for when objects may
have null values themselves.
This commit is contained in:
John Montgomery
2011-04-15 10:01:40 +01:00
parent d04f2c2f76
commit 5d59eada29
3 changed files with 44 additions and 7 deletions
@@ -284,6 +284,27 @@ public class MustacheTest
"parentProperty", "bar"));
}
@Test(expected = MustacheException.class)
public void testMissingValue () {
String tmpl = "{{ missing }} {{ notmissing }}";
Mustache.compiler().compile(tmpl).
execute(Collections.singletonMap("notmissing", "bar"));
}
@Test public void testMissingValueWithDefault () {
String tmpl = "{{ missing }}{{ notmissing }}";
String result = Mustache.compiler().missingVariableValue("").compile(tmpl).
execute(Collections.singletonMap("notmissing", "bar"));
assertEquals("bar", result);
}
@Test public void testMissingValueWithDefaultNonEmptyString () {
String tmpl = "{{ missing }}{{ notmissing }}";
String result = Mustache.compiler().missingVariableValue("foo").compile(tmpl).
execute(Collections.singletonMap("notmissing", "bar"));
assertEquals("foobar", result);
}
protected void test (Mustache.Compiler compiler, String expected, String template, Object ctx)
{
assertEquals(expected, compiler.compile(template).execute(ctx));