配置thymeleaf模板属性
时间: 2023-10-13 10:13:28 浏览: 85
thymeleaf使用模板
可以在Spring Boot的配置文件(application.yml或application.properties)中指定Thymeleaf的相关属性,例如:
```yaml
spring:
thymeleaf:
cache: false # 关闭缓存
mode: HTML # 模板渲染模式,可以是HTML、XML、TEXT、JAVASCRIPT、CSS
encoding: UTF-8 # 模板编码
prefix: classpath:/templates/ # 模板所在路径,可以是classpath:/templates/或file:/path/to/templates/
suffix: .html # 模板后缀
template-resolver-order: 1 # 模板解析器的优先级,数字越小优先级越高
```
除了在配置文件中指定属性,也可以通过Java代码配置Thymeleaf,例如:
```java
@Configuration
public class ThymeleafConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("classpath:/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setOrder(1);
return viewResolver;
}
}
```
在这个配置类中,我们定义了一个SpringResourceTemplateResolver来指定模板所在路径和文件后缀,并设置了禁用缓存、编码等属性。然后创建了一个SpringTemplateEngine并设置了模板解析器,并启用了SpringEL编译器。最后创建了一个ThymeleafViewResolver并设置了模板引擎和字符编码,并指定了解析器的优先级。
阅读全文