Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom Spring EL function in Thymeleaf?

I write a Function like this:

public interface SUtils {

    static String reverseString(String input) {
        StringBuilder backwards = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            backwards.append(input.charAt(input.length() - 1 - i));
        }
        return backwards.toString();
    }
}

And register this function with StandardEvaluationContext.registerFunction. And in controller I use @Value("#{#reverseString('hello')}") can get the value. but in thymeleaf when I use ${reverseString('hello')} got an error Exception evaluating SpringEL expression: "reverseString('hello')".

How to use custom spel in thymeleaf?

like image 683
Maxim Rong Avatar asked Aug 16 '17 07:08

Maxim Rong


People also ask

How do you pass parameters in Thymeleaf?

Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client to server like: https://example.com/query?q=Thymeleaf+Is+Great! In the above example if parameter q is not present, empty string will be displayed in the above paragraph otherwise the value of q will be shown.

How do you use Thymeleaf in spring?

You can use Thymeleaf templates to create a web application in Spring Boot. You will have to follow the below steps to create a web application in Spring Boot by using Thymeleaf. In the above example, the request URI is /index, and the control is redirected into the index. html file.

How do you add an object to Thymeleaf?

Yes it is possible to do it in Thymeleaf since it's using Object-Graph Navigation Language for evaluating expression values - content of ${...} block. You can access public methods normally on your model object so calling boolean List#add(E e) method works.


2 Answers

What I usually do, is to define Thymeleaf utility classes like this as a Bean using @Component. In Spring EL you can then simply refer to them using @ with auto-detection. So there is no need to register them.

@Component
public interface SUtils {

  static String reverseString(String input) {
    // ...
  }
}

<span th:text="${@sUtils.reverseString('hello')}"></span>
like image 78
RoToRa Avatar answered Sep 23 '22 01:09

RoToRa


Not in front of a way to test, but offhand try using the static call:

th:text="${T(com.package.SUtils).reverseString('hello')}"

like image 25
vphilipnyc Avatar answered Sep 23 '22 01:09

vphilipnyc