Text Templates in Java
Java offers built-in support for creating dynamic content or showing customized output to the user with the java.util.StringTemplate
class introduced in Java 21. For earlier versions, you can use third-party libraries like FreeMarker or Thymeleaf for similar functionality.
import java.util.StringTemplate;
import java.util.List;
import java.util.Map;
public class TextTemplates {
public static void main(String[] args) {
// We can create a new template using StringTemplate
StringTemplate t1 = StringTemplate.of("Value is \{value}\n");
// By "processing" the template we generate its text with
// specific values for its placeholders.
System.out.print(t1.process(Map.of("value", "some text")));
System.out.print(t1.process(Map.of("value", 5)));
System.out.print(t1.process(Map.of("value", List.of("Java", "Kotlin", "Scala", "Groovy"))));
// If the data is a record we can use the field names directly in the template
record Person(String name) {}
StringTemplate t2 = StringTemplate.of("Name: \{name}\n");
System.out.print(t2.process(new Person("Jane Doe")));
// The same applies to maps
System.out.print(t2.process(Map.of("name", "Mickey Mouse")));
// Conditional execution can be achieved using the ternary operator
StringTemplate t3 = StringTemplate.of("\{value ? 'yes' : 'no'}\n");
System.out.print(t3.process(Map.of("value", "not empty")));
System.out.print(t3.process(Map.of("value", "")));
// For looping through collections, we can use String.join()
// in combination with StringTemplate
StringTemplate t4 = StringTemplate.of("Range: \{String.join(' ', items)}\n");
System.out.print(t4.process(Map.of("items", List.of("Java", "Kotlin", "Scala", "Groovy"))));
}
}
To run the program, compile and execute it using the java
command:
$ javac TextTemplates.java
$ java TextTemplates
Value is some text
Value is 5
Value is [Java, Kotlin, Scala, Groovy]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Java Kotlin Scala Groovy
In this Java example, we’re using the StringTemplate
class introduced in Java 21. It provides a simple way to create templates with placeholders. The placeholders are defined using \{...}
syntax.
For conditional logic and loops, Java’s StringTemplate
doesn’t provide direct support like Go’s text/template package. Instead, we use Java’s ternary operator for conditional execution and String.join()
for iterating over collections.
If you’re using an earlier version of Java or need more complex templating features, consider using third-party libraries like FreeMarker or Thymeleaf, which offer more advanced templating capabilities similar to Go’s text/template package.