ThymeleafでBootstrapのソースコードを呼び出し

ThymeleafでBootstrapのソースコードを呼び出し

ThymeleafでBootstrapを使用するには、BootstrapのCSSとJavaScriptファイルをHTMLテンプレートにリンクする必要があります。
以下の手順で設定できます。

1. BootstrapのCDNを使用する方法

Bootstrapの公式CDNを利用して、簡単にBootstrapのスタイルとスクリプトを取り込むことができます。
以下のコードをThymeleafテンプレートのセクションに追加してください。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Bootstrap Example</title>
 <!-- Bootstrap CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.5.2/css/bootstrap.min.css}">
</head>
<body>
 <!-- Your content here -->
 
 <!-- Bootstrap JS and dependencies -->
 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" th:src="@{/webjars/jquery/3.5.1/jquery.slim.min.js}"></script>
 <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" th:src="@{/webjars/popper.js/2.11.6/umd/popper.min.js}"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.5.2/js/bootstrap.min.js}"></script>
</body>
</html>

2. ローカルにBootstrapを導入する方法

プロジェクト内にBootstrapのCSSとJSファイルをダウンロードして、ローカルリソースとして参照することもできます。
以下はその一例です。

Bootstrapのファイルをプロジェクト内に配置
例えば、src/main/resources/static/css に bootstrap.min.css、src/main/resources/static/js に bootstrap.min.js を配置します。

Thymeleafテンプレートでリンクする
以下のようにリンクを指定します。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bootstrap Example</title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body>
  <!-- Your content here -->
  
  <!-- Bootstrap JS and dependencies -->
  <script src="/js/bootstrap.min.js"></script>
</body>
</html>

どちらの方法も、ThymeleafでBootstrapのスタイルとスクリプトを利用するのに有効です。
必要に応じてCDNとローカルリソースのどちらかを選んでください。