Search in sources :

Example 1 with TemplateContext

use of com.github.mustachejava.TemplateContext in project dcos-commons by mesosphere.

the class TemplateUtils method renderMustache.

/**
 * Renders a given Mustache template using the provided value map, returning any template parameters which weren't
 * present in the map.
 *
 * @param templateName descriptive name of template to show in logs
 * @param templateContent String representation of template
 * @param values Map of values to be inserted into the template
 * @param missingValues List where missing value entries will be added for any template params in
 *     {@code templateContent} which are not found in {@code values}
 * @return Rendered Mustache template String
 */
public static String renderMustache(String templateName, String templateContent, Map<String, String> values, final List<MissingValue> missingValues) {
    StringWriter writer = new StringWriter();
    DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory();
    mustacheFactory.setObjectHandler(new ReflectionObjectHandler() {

        @Override
        public Binding createBinding(String name, final TemplateContext tc, Code code) {
            return new MissingValueBinding(this, name, tc, code, missingValues);
        }
    });
    Map<String, Object> objEnv = new HashMap<>();
    for (Map.Entry<String, String> entry : values.entrySet()) {
        if (StringUtils.equalsIgnoreCase(entry.getValue(), "false") || StringUtils.equalsIgnoreCase(entry.getValue(), "true")) {
            objEnv.put(entry.getKey(), Boolean.valueOf(entry.getValue()));
        } else {
            objEnv.put(entry.getKey(), entry.getValue());
        }
    }
    mustacheFactory.compile(new StringReader(templateContent), templateName).execute(writer, objEnv);
    return writer.toString();
}
Also used : GuardedBinding(com.github.mustachejava.reflect.GuardedBinding) Binding(com.github.mustachejava.Binding) DefaultMustacheFactory(com.github.mustachejava.DefaultMustacheFactory) HashMap(java.util.HashMap) TemplateContext(com.github.mustachejava.TemplateContext) ValueCode(com.github.mustachejava.codes.ValueCode) Code(com.github.mustachejava.Code) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) ReflectionObjectHandler(com.github.mustachejava.reflect.ReflectionObjectHandler) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Aggregations

Binding (com.github.mustachejava.Binding)1 Code (com.github.mustachejava.Code)1 DefaultMustacheFactory (com.github.mustachejava.DefaultMustacheFactory)1 TemplateContext (com.github.mustachejava.TemplateContext)1 ValueCode (com.github.mustachejava.codes.ValueCode)1 GuardedBinding (com.github.mustachejava.reflect.GuardedBinding)1 ReflectionObjectHandler (com.github.mustachejava.reflect.ReflectionObjectHandler)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1