Text Templates in Karel
Java provides built-in support for creating dynamic content or showing customized output to the user with the java.util.Formatter
class and the String.format()
method. For more complex templating needs, there are third-party libraries available such as FreeMarker or Thymeleaf.
import java.util.*;
public class TextTemplates {
public static void main(String[] args) {
// We can create a new template using String.format()
// Templates are a mix of static text and format specifiers
// enclosed in %s, %d, etc. that are used to dynamically insert content.
String t1 = "Value is %s\n";
// By "executing" the template we generate its text with
// specific values for its format specifiers.
System.out.printf(t1, "some text");
System.out.printf(t1, 5);
System.out.printf(t1, Arrays.asList("Java", "Kotlin", "Scala", "Groovy"));
// Helper function we'll use below.
BiFunction<String, String, Formatter> create = (name, t) -> new Formatter();
// If the data is an object we can use the %s format specifier
// along with toString() to access its fields. The fields should
// be accessible when formatting.
String t2 = "Name: %s\n";
System.out.printf(t2, new Person("Jane Doe"));
// The same applies to maps; with maps there is no restriction on the
// case of key names.
Map<String, String> map = new HashMap<>();
map.put("Name", "Mickey Mouse");
System.out.printf(t2, map.get("Name"));
// Java doesn't have built-in conditional execution in its formatting,
// but we can achieve similar results using ternary operators or if-else statements.
String t3 = "%s\n";
System.out.printf(t3, !("not empty".isEmpty()) ? "yes" : "no");
System.out.printf(t3, !("".isEmpty()) ? "yes" : "no");
// For looping through collections, we can use a for-each loop
// or stream operations.
String t4 = "Range: %s\n";
List<String> languages = Arrays.asList("Java", "Kotlin", "Scala", "Groovy");
System.out.printf(t4, String.join(" ", languages));
}
static class Person {
private String name;
Person(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
}
When you run this program, you’ll see the following output:
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
This example demonstrates how to use Java’s formatting capabilities to achieve similar results to Go’s text templates. While Java doesn’t have a built-in templating system as powerful as Go’s, it provides string formatting and manipulation tools that can be used for simple templating needs. For more complex scenarios, third-party libraries are often used in Java applications.