How do I format text in Apache FreeMarker?
I would like to add a new formatter that would format the value (taken from json). For example, the text ANIMAL
would be formatted to Animal
(ideally it would also work if the word animal
was lowercase and it would format it to Animal
).
I checked the available built-in functions for strings, but I can't find this particular one. https://freemarker.apache.org/docs/ref_builtins_string.html
CodePudding user response:
You can create a method that formats the word you want. In the example my method format
enters a String which no matter how it is structured, it returns it with the first one in uppercase and the others in lowercase. You can see that I enter the word "ANIMAL" and it would return "Animal". It doesn't matter if the word is "aNiMaL", it always returns the same.
public class Main {
public static void main(String[] args) {
String str = "ANIMAL";
System.out.println(format(str)); // result: Animal
}
public static String format(String input) {
return input.substring(0, 1).toUpperCase() input.substring(1).toLowerCase();
}
}
For use in FreeMarker: Modify the getters in the attributes where you want to format the String.
public class entity {
private String a;
public String getA() {
return format(this.a);
}
}
CodePudding user response:
You could combine ?lower_case
and ?cap_first
:
${"ANIMAL"?lower_case?cap_first}
Results in:
Animal