1. 序章

このクイックチュートリアルでは、ThymeleafテンプレートでCSSとJavaScriptを使用する方法を学習します。

まず、予想されるフォルダー構造を調べて、ファイルを配置する場所を確認します。 その後、Thymeleafテンプレートからこれらのファイルにアクセスするために何をする必要があるかを確認します。

まず、ページにCSSスタイルを追加してから、JavaScript機能を追加します。

2. 設定

アプリケーションでThymeleafを使用するために、Thymeleaf用のSpring BootスターターをMaven構成に追加しましょう。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

3. 基本例

3.1. ディレクトリ構造

さて、念のために言っておきますが、Thymeleafは、SpringBootアプリケーションと簡単に統合できるテンプレートライブラリです。 デフォルトでは、Thymeleafはこれらのテンプレートをsrc / main / resources / templatesフォルダーに配置することを想定しています。サブフォルダーを作成できるため、cssandjsというサブフォルダーを使用します。例。

CSSおよびJavaScriptファイルの場合、デフォルトのディレクトリはsrc / main / resources/staticです。 作成しましょう static / styles / cssandjs static / js / cssandjs それぞれCSSファイルとJSファイルのフォルダー。

3.2. CSSの追加

static / styles /cssandjsフォルダーにmain.cssという名前の簡単なCSSファイルを作成し、いくつかの基本的なスタイルを定義しましょう。

h2 {
    font-family: sans-serif;
    font-size: 1.5em;
    text-transform: uppercase;
}

strong {
    font-weight: 700;
    background-color: yellow;
}

p {
    font-family: sans-serif;
}

次に、これらのスタイルを使用するために、 templates /cssandjsフォルダーにstyledPage.htmlという名前のThymeleafテンプレートを作成しましょう。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Add CSS and JS to Thymeleaf</title>
    <link th:href="@{/styles/cssandjs/main.css}" rel="stylesheet" />
</head>
<body>
    <h2>Carefully Styled Heading</h2>
    <p>
        This is text on which we want to apply <strong>very special</strong> styling.
    </p>
</body>
</html>

Thymeleafの特別なth:href属性を持つリンクタグを使用してスタイルシートをロードします。 予想されるディレクトリ構造を使用した場合は、 src / main / resources /staticの下にパスを指定するだけで済みます。 この場合、それは/styles/cssandjs/main.cssです。 @ {/ styles / cssandjs / main.css} 構文は、ThymeleafのURLリンクの方法です。

アプリケーションを実行すると、スタイルが適用されていることがわかります。

 

 

 

 

3.3. JavaScriptを使用する

次に、JavaScriptファイルをThymeleafページに追加する方法を学習します。

src / main / resources / static / js / cssandjs /actions.jsのファイルにJavaScriptを追加することから始めましょう。

function showAlert() {
    alert("The button was clicked!");
}

次に、Thymeleafテンプレートに戻って、