我的应用程序中有一个主题解析器。有两个主题:深色和白色。
<p th:text="${param.theme}">
</p>
这将返回当前主题,深色或白色。但是,
<p th:if="${param.theme == 'white'}">
white theme
</p>
不输出任何内容。
我希望它实现主题切换。如何运作?
Java配置代码。
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/");
}
答案 0 :(得分:1)
尝试一下。
public class DataInterceptor extends HandlerInterceptorAdapter
{
@Override public void postHandle( HttpServletRequest request,
HttpServletResponse response, Object handler, ModelAndView
modelAndView ) throws Exception
{
if( modelAndView != null )
{
setup( modelAndView.getModel(), request );
}
}
private void setup( Map<String, Object> model, HttpServletRequest request )
{
String theme = RequestContextUtils.getTheme( request ).getName();
model.put( "theme", theme);
}
}
答案 1 :(得分:1)
尝试将主题参数转换为字符串(使用thymleaf表达式#{}),然后将其与主题名称进行比较
如下:
<p th:if="${#strings.toString(param.theme) == 'white'}">
white theme
</p>