Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf - how to add a custom util?

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?

like image 270
WildDev Avatar asked Jun 19 '16 08:06

WildDev


People also ask

How do I include a JavaScript file in Thymeleaf?

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.

How do I add CSS to 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.

How do I configure Thymeleaf?

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.

How do you use attributes in 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.


1 Answers

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;
            }
        };
    }
}
like image 61
ryanp Avatar answered Sep 23 '22 03:09

ryanp