是否有一种方法可以将胸里叶模板存储在resources
或webapp
中,而是在与类相同的包中?例如这样的结构:
com
example
myapp
foo
Foo.class
Template.html
bar
Bar.class
Template.html
OtherTemplate.html
我该如何配置Spring和Thymeleaf以实现这一点?
需要在WebMvcConfigurer
中定义一个ClassLoaderTemplateResolver
。
在下面的示例中,我的模板所在的基本包是net.yadaframework.views
(在您的示例中应该是com.example.myapp
)。当我从控制器返回一个视图时,路径是相对于那个包的,所以在你的例子中是"/foo/Template"
。patterns
集应该包含基本包的子文件夹,所以在您的示例中是"/foo/*"
和"/bar/*"
。
@EnableWebMvc
@ComponentScan(basePackages = { "net.yadaframework.views" })
public class YadaWebConfig implements WebMvcConfigurer {
public ClassLoaderTemplateResolver yadaTemplateResolver() {
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("net/yadaframework/views");
/* From the tutorial:
When several template resolvers are applied, it is recommended to specify patterns
for each template resolver so that Thymeleaf can quickly discard those template resolvers
that are not meant to resolve the template, enhancing performance. Doing this is not a
requirement, but a recommendation
*/
Set<String> patterns = new HashSet<>();
patterns.add("/yada/*"); // Start with "yada". Patterns are NOT regexp
patterns.add("/yadacms/*"); // Start with "yadacms". Patterns are NOT regexp
resolver.setResolvablePatterns(patterns);
resolver.setSuffix(".html");
resolver.setCharacterEncoding("UTF-8");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(true);
resolver.setOrder(10);
return resolver;
}