I have a theme resolver in my application. There are two themes: dark and white.
<p th:text="${param.theme}">
</p>
This returns the current theme, dark or white. However, the
<p th:if="${param.theme == 'white'}">
white theme
</p>
outputs nothing.
I want this to implement theme switching. How to make it work?
The Java configuration code.
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicationContext;
@Bean
public SpringResourceTemplateResolver templateResolver() {
var templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
var templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Bean
public ViewResolver viewResolver() {
var resolver = new ThymeleafViewResolver();
var registry = new ViewResolverRegistry(null, applicationContext);
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
return resolver;
}
@Bean
public ThemeSource themeSource() {
var themeSource = new ResourceBundleThemeSource();
themeSource.setBasenamePrefix("themes/");
return themeSource;
}
@Bean
public ThemeResolver themeResolver(){
var resolver = new CookieThemeResolver();
resolver.setCookieMaxAge(604800);
resolver.setCookieName("mytheme");
resolver.setDefaultThemeName("dark");
return resolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
var themeChangeInterceptor = new ThemeChangeInterceptor();
themeChangeInterceptor.setParamName("theme");
registry.addInterceptor(themeChangeInterceptor);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
}
try to convert theme param to string ( using thymleaf expression #{} ) and then compare it to your theme name
as below :
<p th:if="${#strings.toString(param.theme) == 'white'}">
white theme
</p>