Created
July 3, 2013 16:37
-
-
Save kristopherjohnson/5920254 to your computer and use it in GitHub Desktop.
Configure JMustache to work like GRMustache, to allow the same Mustache templates to be used on iOS and Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.kristopherjohnson.mustache; | |
// from jmustache-1.8.jar | |
import com.samskivert.mustache.Mustache; | |
/** | |
* Convenience class wrapper around the functionality provided by the JMustache library. | |
* | |
* Wherever possible, the template rendering behavior is configured to be compatible with the | |
* GRMustache library, so that the same templates can be used on iOS and Android. | |
*/ | |
public class MustacheRenderer | |
{ | |
private final Mustache.Compiler compiler; | |
/** | |
* Constructor | |
*/ | |
public MustacheRenderer() | |
{ | |
compiler = createCompiler(); | |
} | |
/** | |
* Render a template taking values from the specified execution context | |
* | |
* @param template | |
* Mustache template | |
* @param context | |
* Execution context | |
* @return String | |
*/ | |
public String renderTemplate(String template, Object context) | |
{ | |
String result = compiler.compile(template).execute(context); | |
return result; | |
} | |
/** | |
* Construct a Mustache.Compiler, configured to maximize compatibility with GRMustache | |
* | |
* @return Mustache.Compiler | |
*/ | |
private Mustache.Compiler createCompiler() | |
{ | |
Mustache.Compiler compiler = Mustache.compiler(); | |
// Configure compiler to generate an empty string for any missing value, | |
// instead of throwing an exception. | |
compiler = compiler.defaultValue(""); | |
// Configure compiler to treat empty strings as "false" values | |
// | |
// Note: While JMustache 1.8 does provide option to treat empty strings as false, it | |
// does not work properly with inverted sections. See | |
// https://github.com/samskivert/jmustache/issues/39. | |
// | |
// To work around this, you will have to replace empty strings with false or null if you | |
// use the values to control inverted sections. | |
compiler = compiler.emptyStringIsFalse(true); | |
return compiler; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment