7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【 Thymeleaf】複数項目の間に「/(スラッシュ)」を適度に入れる

Last updated at Posted at 2023-07-03

複数項目を表示する際に、項目を見やすくするように「/」を適度に入れる実装をしました。メモして残しておきます。

やりたいこと

バックエンド側からフロント側に、複数の項目が渡ってきます。複数の項目を画面に表示する際に、項目間に「/(スラッシュ)」を入れる。
項目は、毎回同じ値、同じ数が渡ってこない前提で、検討する。

実装

Javaとthymeafを使って実装をします。

SlashController.java
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SlashController {
	
	@GetMapping("/slash")
	public String displayIndex(Model model) {
		model.addAttribute("category", "果物");
		model.addAttribute("apple", "1");
		model.addAttribute("orange", "1");
		model.addAttribute("grape", "1");
		return "slash/index";
	}
}

まず、Javaで「~/slash」でリクエストされると、「category」「apple」「orange」「grape」を画面に渡すコードを書きます。本稿では「thymeaf」での制御を示したいので、テストデータ的な位置付けです。
「apple」「orange」「grape」は0または1が入ってくる想定です。

index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta charset="utf-8" />
  </head>
  <body>
    
    <table border="1">
      <thead>
        <tr>
          <th>分類</th>
          <th>内容</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td th:text="${category}"></td>
          <td th:text="${(apple == '1' ? 'りんご' : '') +
            (apple == '1' && orange == '1' ? '/' : '') +
            (orange == '1' ? 'オレンジ' : '') +
            ((apple == '1' || orange == '1') && grape == '1' ? '/' : '') +
            (grape == '1' ? 'ぶどう' : '')}"></td>
        </tr>
      </tbody>
    </table>
    
  </body>
</html>

テーブルタグとthymeafを組み合わせて、バックエンド側からの値を受け取ります。「apple」「orange」「grape」が1のときは、対応する日本語名に置き換えています。そして、↓スクショのように「内容」の列に「りんご/オレンジ/ぶどう」と項目間に「/」が入っています。

画面
image.png

「/」を入れる部分はこちらです。「/」の前の項目と次の項目があれば、「/」をいれるように記載しています。こうすると、バックエンドから値が2つだけ渡ってきたとしても、項目間だけに「/」が入ります。

(apple == '1' && orange == '1' ? '/' : '') +
((apple == '1' || orange == '1') && grape == '1' ? '/' : '') +

ひとまず、やりたいことは表現できました。

もし誰かの役に立ったら、嬉しいです。
最後まで読んでいただいた方、ありがとうございました。

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?