3

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 ANIMALwould be formatted to Animal(ideally it would also work if the word animalwas 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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
diho472
  • 69
  • 5
  • Does this answer your question? [How to capitalize the first letter of word in a string using Java?](https://stackoverflow.com/questions/5725892/how-to-capitalize-the-first-letter-of-word-in-a-string-using-java) – Risalat Zaman Jan 03 '23 at 16:59

2 Answers2

1

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);
    }
}
1

You could combine ?lower_case and ?cap_first:

${"ANIMAL"?lower_case?cap_first}

Results in:

Animal
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102