在Spring Boot中使用templates/includes

No *_*One 3 java spring spring-mvc spring-boot

即时'开发'使用Spring Boot创建的应用程序,我不太确定如何管理模板.

我有两种方法可以做到这一点:

使用自定义标记并将HTML/JSP文件的值作为String返回并使用它

像这样的东西

<th:header></th:header>
<!-- This would be the header (The implementation of this tag in Java) -->

<body>
  Things that are not common


  <th:footer></th:footer>
  <!-- This would be the footer -->
</body>
Run Code Online (Sandbox Code Playgroud)

另一种方式可能是使用包括,但我不太确定如何做到这一点......

不知道是否有另一种使用Spring的方法.希望你能理解我.

先谢谢你:·).

Mar*_*one 6

你可以使用Thymeleaf.然后你可以使用

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head th:replace="common/header :: common-header" />

<body>

    <div th:replace="common/navbar :: common-navbar" />
    <your content here>
</body
</html>
Run Code Online (Sandbox Code Playgroud)

然后你会在不同的文件中使用common-header和common-navbar thymeleaf片段(请注意公共文件中的th:片段.另请注意,这些文件位于公共文件夹下):

<head th:fragment="common-header">

<title>DevOps Buddy</title>

<!-- Bootstrap core CSS -->
<link th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}"
      rel="stylesheet" media="screen" />

<!-- Custom styles for this template -->
<link type="text/css" th:href="@{/css/styles.css}" rel="stylesheet" media="screen"/>
Run Code Online (Sandbox Code Playgroud)

所以

<div th:fragment="common-navbar" class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a th:text="#{navbar.home.text}" href="/"></a></li>
                <li><a th:text="#{navbar.about.text}" href="/about"></a></li>
                <li><a th:text="#{navbar.contact.text}" href="/contact"></a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li th:if="${#authorization.expression('!isAuthenticated()')}">
                    <a th:href="@{/login}" th:text="#{navbar.login.text}" />
                </li>
                <li th:if="${#authorization.expression('isAuthenticated()')}">
                    <form id="f" th:action="@{/logout}" method="post" role="form" class="navbar-form">
                        <button type="submit" th:text="#{navbar.logout.text}" class="btn btn-primary" />
                    </form>
                </li>
            </ul>
        </div><!--/.nav-collapse -->
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)