Home > Software design >  Is there any way to separate css and js libraries listing in head tag and reuse anytime in thymeleaf
Is there any way to separate css and js libraries listing in head tag and reuse anytime in thymeleaf

Time:09-23

I am a newbie to Thymeleaf and Spring boot. I am working in a project that I dont want to rewrite js css libraries lising (actually this is about including js css libraries) two many times in two many files. Ex: I have a login.html, register.html, dashboard.html.

These files share the same js and css libraries like styling, bootstrap, jquery, font-awesome...etc which will be defined (or listed) in tag. Instead of rewriting js and css libraries definition many time, I just wonder I can find a way to separate js and css libraries inclusion and make it a completely individual file to reuse anytime.

Is there any way to separate js, css libraries inclusion from login.html and register.html to avoid rewrite two many times?

Sorry for my bad english. I really appreciate if anyone can help or suggest.

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>

CodePudding user response:

you can use fragments:

  • create a folder called "fragments" and in that put a 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>
    
  • then in your individual template include the next markup where you needed:

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

with this you can reuse html and save typing.

  • Related