ThymeleafでHTMLのタグをエスケープせずにそのまま出力する方法
ThymeleafでHTMLのタグをエスケープせずにそのまま出力するには、th:utextを使用します。
これにより、HTMLタグがエスケープされずにそのまま表示されます。
以下は、Thymeleafテンプレートとコントローラの処理を含む例です。
Thymeleafテンプレート (template.html)
<!DOCTYPE html> <html> <head> <title>タグ出力の例</title> </head> <body> <p th:utext="${htmlContent}"></p> </body> </html>
コントローラ (ExampleController.java)
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ExampleController { @GetMapping("/showHtml") public String showHtml(Model model) { String htmlContent = "<strong>このテキストは<strong>タグが含まれています。</strong></strong>"; model.addAttribute("htmlContent", htmlContent); return "template"; } }
この例では、htmlContentという変数にHTMLタグを含む文字列を設定し、th:utextを使用してそのまま出力しています。
コントローラでは、htmlContentをモデルに追加し、Thymeleafテンプレートで表示しています。