Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created July 3, 2013 16:37
Show Gist options
  • Save kristopherjohnson/5920254 to your computer and use it in GitHub Desktop.
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
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