【发布时间】:2017-08-17 04:26:02
【问题描述】:
我正在创建 Spring Boot Web 应用程序。出于模板目的,我使用的是百里香。我正在创建单独的 html 页面片段,并从这些片段中创建两个不同的布局。但是,当我连接内容页面时,我没有得到正确的输出。
请检查代码sn-ps/
查看解析器
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public TemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("html5");
return templateResolver;
}
@Bean
public SpringTemplateEngine setTemplateEngine() {
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setTemplateResolver(templateResolver());
return springTemplateEngine;
}
@Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(setTemplateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
目录结构
src/
main/
webapp/
WEB-INF/
views/
fragments/
header.html
footer.html
navBar.html
layouts/
appLayout.html
baseLayout.html
welcome.html
appLayout.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
</head>
<body>
<div th:replace="/fragments/header :: header"></div>
<div th:replace="/fragments/navbar :: navbar"></div>
<div class="container">
<div layout:fragment="content">
<p>Content goes here...</p>
</div>
<footer>
<div th:replace="/fragments/footer :: footer"></div>
</footer>
</div>
</body>
</html>
页脚片段footer.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:fragment="footer">
Footer
</div>
</body>
</html>
使用此方法创建不同的片段。
主方法类又名启动
@ComponentScan(basePackages={"xyz.abc"})
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
System.out.println("Started");
SpringApplication.run(AppApplication.class, args);
}
}
welcome.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layouts/appLayout}">
<head>
</head>
<body>
<th:block layout:fragment="content">
<div class="hero-unit">
<h1>My Content</h1>
</div>
</th:block>
</body>
</html>
现在当我访问服务器时,我只得到welcome.html 而没有从appLayout 和fragments 得到任何东西
我错过了什么?
还有一个问题,我经历了许多项目,其中一些将views 保留在src/main/resource 之下,而我将其保留在src/main/web/WEB-INF 之下这两种方法有什么区别?
【问题讨论】:
-
第二个问题请看this。
-
非常感谢。
-
您是否已将
LayoutDialect添加到SpringTemplateEngine中? -
没有。它是什么?以及如何/为什么要写它?
-
尝试删除片段路径中的正斜杠
标签: spring spring-mvc spring-boot thymeleaf