Class 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 Detail

      • Templator

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

      • 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(readResource("/message_template.txt", valuesMap));
        Parameters:
        templatePath - template to merge
        values - values to merge into a template
        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