Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text formatting (first letter uppercase, rest lowercase) in Apache FreeMarker

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

like image 241
diho472 Avatar asked Oct 23 '25 14:10

diho472


2 Answers

You could combine ?lower_case and ?cap_first:

${"ANIMAL"?lower_case?cap_first}

Results in:

Animal
like image 172
Jasper de Vries Avatar answered Oct 26 '25 03:10

Jasper de Vries


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);
    }
}
like image 20
Manuel Motta Avatar answered Oct 26 '25 03:10

Manuel Motta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!