Class Templator

java.lang.Object
org.javalite.common.Templator

public class Templator extends Object
Simple implementation of small quick templates filled with dynamic data. An example of a template:
     Hello, {{name}}!
 
Usage:
     Templator templator = new Templator("/hello_template.txt");
     System.out.println(templator.merge(map("name", "Kyla"))); // prints: Hello, Kyla!
 

Note: Yes, I'm aware of existence of Mustache, Freemarker, Velocity, etc. This implementation is for quickly loading small snippets of text merged with data. The goal is to eliminate code pollution. If you need more power, use bigger frameworks.
Author:
Igor Polevoy on 9/30/16.
  • Constructor Details

    • Templator

      public Templator(String templatePath)
      Parameters:
      templatePath - path to a template on classpath
  • Method Details

    • merge

      public String merge(Map<String,​?> values)
      This method is used in repeated operations, since it will load a resource once.
      Parameters:
      values - values to merge into a template
      Returns:
      result of merging
    • mergeFromPath

      public static String mergeFromPath(String templatePath, Map<String,​?> values)
      This method is used in one-off operations, where it is OK to load a template every time. Example: String result = Templator.mergeFromPath("/message_template.txt", valuesMap);
      Parameters:
      templatePath - template to merge
      values - values to merge into a template
      Returns:
      result of merging
    • mergeFromPath

      public static String mergeFromPath(String templatePath, Map<String,​?> values, boolean stripWhitespace)
      This method is used in one-off operations, where it is OK to load a template every time. Example: String result = Templator.mergeFromPath("/message_template.txt", valuesMap);
      Parameters:
      templatePath - template to merge
      values - values to merge into a template
      stripWhitespace - - true to strip whitespace, false to keep the template intact
      Returns:
      result of merging
    • mergeFromTemplate

      public static String mergeFromTemplate(String template, Map<String,​?> values)
      Merges from string as template.
      Parameters:
      template - template content, with placeholders like: {{name}}
      values - map with values to merge
    • mergeFromTemplate

      public static String mergeFromTemplate(String template, Map values, boolean stripWhitespace)
      Merges from string as template.
      Parameters:
      template - template content, with placeholders like: {{name}}
      values - properties with values to merge
      stripWhitespace - true to strip \n\r and space.