boycod3
boycod3

Reputation: 5319

use property value in thymeleaf th:if condition

Basically I have configuration in property file

data.enabled = true

and I have added a POJO class for that

@Configuration
@PropertySource(value = {"classpath:dataconfig.properties"})
public class DataProperties {
    private Boolean enabled;
}

and I want to check the enabled property on html tag using thymeleaf.

<li th:if="${DataProperties.getEnabled() == true}"><h3>Hello</h3></li>

Upvotes: 0

Views: 1849

Answers (1)

Patrick
Patrick

Reputation: 12734

First you should add @ConfigurationProperties(prefix="data") to your configuration class.

@Configuration
@PropertySource("classpath:dataconfig.properties")
@ConfigurationProperties(prefix="data")
public class DataProperties {
    private Boolean enabled;

This activates that your variable is directly binded to the property value without using @Value annotation. In your property file you have data.enabled. This means that your prefix is data. So you have to set this, too.

To use the bean in thymeleaf directly you need to use a special command. In your case it should look like that: (see point 5 in the docs)

<li th:if="${@dataProperties.getEnabled() == true}" ><h3>Hello</h3></li>

Addition 1:

To use the same property in other spring beans like controllers you have to autowire your DataProperties

@Controller
public class IndexController {

    @Autowired
    private DataProperties dataProperties;

    @GetMapping("/")
    public String index() {
        dataProperties.getEnabled();
        return "index";
    }

Just to mention it autowire on a field is bad practice. But its your choice to use it like that or autowire on constructor or setter.

Upvotes: 2

Related Questions