Thymeleaf has a number of useful utilities like #strings.capitalize(...)
or #lists.isEmpty(...)
. I'm trying to add a custom one but have no idea how to register this.
Have made a custom Util class:
public class LabelUtil {
public String[] splitDoubleWord(String str) {
return str.split("[A-Z]", 1);
}
}
Now I'm going to use it like this:
<span th:each="item : ${#labels.splitDoubleWord(name)}" th:text="${item}"></span>
Of course, it won't work because I haven't registered the Util and defined #labels
var.
So, the question is how and where to do it?
The one way to add CSS and JS files is to add them to the static folder of src/main/resources and reference it to the Thymeleaf template. Here @{} is the way of linking URL in Thymeleaf.
Adding CSS. We load the stylesheet using the link tag with Thymeleaf's special th:href attribute. If we've used the expected directory structure, we only need to specify the path below src/main/resources/static. In this case, that's /styles/cssandjs/main.
Spring Boot will provide auto-configuration for Thymeleaf. Add spring-boot-starter-thymeleaf dependency in pom. xml to enable this auto-configuration. No other configurations required, Spring Boot will inject all required configuration to work with Thymeleaf.
In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName} , where attributeName in our case is messages . This is a Spring EL expression.
The API for registering a custom expression object has changed in Thymeleaf 3, for example:
public class MyDialect extends AbstractDialect implements IExpressionObjectDialect {
MyDialect() {
super("My Dialect");
}
@Override
public IExpressionObjectFactory getExpressionObjectFactory() {
return new IExpressionObjectFactory() {
@Override
public Set<String> getAllExpressionObjectNames() {
return Collections.singleton("myutil");
}
@Override
public Object buildObject(IExpressionContext context,
String expressionObjectName) {
return new MyUtil();
}
@Override
public boolean isCacheable(String expressionObjectName) {
return true;
}
};
}
}
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