有什么方法可以将 head 标签中列出的 css 和 js 库分开,并在 thymeleaf 模板引擎(spring 引导)中随时重用?

Is there any way to separate css and js libraries listing in head tag and reuse anytime in thymeleaf template engine (spring boot)?

我是 Thymeleaf 和 Spring 引导的新手。我在一个项目中工作,我不想在两个文件中多次重写 js css 库(实际上这是关于包含 js css 库)两次。例如:我有一个 login.html、register.html、dashboard.html。

这些文件共享相同的 js 和 css 库,如样式、bootstrap、jquery、font-awesome...等,它们将在标签中定义(或列出) .与其多次重写 js 和 css 库定义,我只是想知道我能找到一种方法来分离 js 和 css 库包含,并使它成为一个完全独立的文件,以便随时重用。

有什么方法可以将 js、css 库包含与 login.html 和 register.html 分开,以避免多次重写两次?

抱歉我的英语不好。如果有人可以提供帮助或建议,我将不胜感激。

EX: Login.html

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

    <!-- Separate these libraries definition into one individual file, ex: layout.html and include it in any other thymeleaf file   -->
    
    <link rel="shortcut icon" th:href="@{/assets/images/favicon.png}" type="image/x-icon">
    <link rel="icon" th:href="@{/assets/images/favicon.ico}" type="image/x-icon">

    <!-- Google font-->
    <link href="https://fonts.googleapis.com/css?family=Ubuntu:400,500,700" rel="stylesheet">

    <!-- Font Awesome -->
    <link th:href="@{/assets/css/font-awesome.min.css}" rel="stylesheet" type="text/css">

    <!--ico Fonts-->
    <link rel="stylesheet" type="text/css" th:href="@{/assets/icon/icofont/css/icofont.css}">

    <!-- Required Framework -->
    <link rel="stylesheet" type="text/css" th:href="@{/assets/plugins/bootstrap/css/bootstrap.min.css}">

    <!-- waves css -->
    <link rel="stylesheet" type="text/css" th:href="@{/assets/plugins/Waves/waves.min.css}">

    <!-- Style.css -->
    <link rel="stylesheet" type="text/css" th:href="@{/assets/css/main.css}">

</head>
<body>
</body>
</html>

你可以使用片段:

  • 创建一个名为“fragments”的文件夹,并在其中放入 header.html

      <div th:fragment="header">
          <link rel="shortcut icon" th:href="@{/favicon.ico}" type="image/x-icon">
          <link rel="icon" th:href="@{/favicon.ico}" type="image/x-icon">
          <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
          <script th:src="@{/js/jquery.js}"></script>
          <script th:src="@{/js/popper.js}"></script>
          <script th:src="@{/js/bootstrap.min.js}"></script>
      </div>
    
  • 然后在您的个人模板中包含您需要的下一个标记:

      <div th:replace="fragments/header :: header"></div>
    

有了这个,您可以重复使用 html 并节省输入时间。