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?
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.
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.
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.
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>
Not in front of a way to test, but offhand try using the static call:
th:text="${T(com.package.SUtils).reverseString('hello')}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With