我即将重写一个 Web 平台,并且我正在使用 Spring Boot/Spring MVC。该平台的主要部分是网站。我正在努力决定使用哪个模板引擎。 Thymeleaf 似乎是推荐的,而 JSP 则不鼓励。我不确定我的要求是否不寻常,至少对我来说听起来不是这样:
- 我不想在不同的模板中重复自己,它们应该全部显示在“主模板/布局”内
- 主模板/布局将具有导航和页脚,其中包含动态内容(例如,不仅仅是动态的主要内容)
1) 对于 Thymeleaf,据我所知,使用布局将是推荐的(唯一?)方法。然而,在我看来,所有动态内容仍然在每个模板中生成(其中使用 layout:fragment
属性流入布局)。这听起来不太理想,因为这意味着我仍然必须在每个模板中生成布局的动态部分。是否无法在 Thymeleaf 布局中包含动态内容,其中内容(菜单、页脚、twitter-feed 等)是与实际内容模板分开生成的?
2) JSP 似乎能够相当轻松地解决这个问题,使用布局的自定义标记,其中有 <jsp:include>
- 动态内容的标签和 <jsp:doBody>
-实际内容模板的标签。然而,通过阅读 Spring Boot 文档,我的印象是鼓励使用与 JSP 不同的模板引擎。然而,上述方法可以让我定义 header.jsp
, navigation.jsp
, footer.jsp
和twitterFeed.jsp
动态生成内容(基于数据库内容、登录用户等),而实际的内容模板纯粹专注于要显示的内容。我在 Thymeleaf 和 JSP 的比较中遗漏了什么,为什么我不选择 JSP 作为我项目的模板引擎?
3) 使用 2) 中提到的方法,我是否只能将所有 Java 逻辑放入主布局中包含的模板的 JSP 中(页眉、导航、页脚、twitter-feed),或者是否有一个使用类似 Controller 的类来支持这些 stub 的更好方法是什么?
4)是否有其他模板引擎可以与 Spring MVC/Spring Boot 很好地集成,这将是比上述任何一个更好的选择?
最佳答案
使用可以使用Thymeleaf Ultraq Layout创建一个基本模板,它将充当其他模板的装饰器,如下所示:
基本模板.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">Sample</title>
<meta name="description" content=""/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- all CSS links here -->
</head>
<body>
<div class="container">
<div class="content">
<div layout:fragment="page_content">
<!-- Content from other pages which decorate using this template -->
</div>
</div>
</div>
<!-- /.container -->
<!-- All script tags here -->
<th:block layout:fragment="scripts">
<!-- If you have any page specific scripts -->
</th:block>
</body>
</html>
然后其他页面将使用上面的模板作为装饰器,如下所示:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{base-template}">
<head>
<title>This page title</title>
</head>
<div layout:fragment="page_content">
<!-- content for this page -->
</div>
<th:block layout:fragment="scripts">
<!-- add any scripts related to this page -->
</th:block>
</html>
语法 ~{base-template}
用于 Thymeleaf 3 及以上版本。
您可以继续执行上述方法,而不要在其他页面上重复导航、页眉和页脚。
关于java - 推荐模板引擎,减少动态内容冗余(Spring Boot),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121576/