You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thymeleaf的th:title属性中解析Summernote生成的HTML内容?

Got it, let's break this down. The issue here is two-fold: first, Thymeleaf's th:title attribute treats values as plain text by default (unlike th:utext which renders HTML in element content), and second, browsers don't support rendering HTML in the title attribute at all—even if you managed to inject HTML tags there, they'd just show up as plain text instead of styled content.

So what you really need is to extract the plain text content from your HTML string to use as the title value. Here are two solid ways to do this in Thymeleaf:

1. Use Thymeleaf's Built-in String Utilities

Thymeleaf has a #strings utility class that can strip HTML tags directly. Combine it with escapeXml to make sure any special characters are safely handled for attribute values:

<!-- Assuming your Summernote-generated HTML is stored in ${summernoteContent} -->
<div th:title="${#strings.escapeXml(#strings.stripTags(summernoteContent))}">
  Hover over me to see the clean title
</div>
  • #strings.stripTags() removes all HTML tags from the input, leaving just the raw text ("Test" in your example).
  • #strings.escapeXml() escapes characters like quotes or ampersands to prevent invalid HTML attribute syntax.

2. Use a Custom Utility Method (More Robust for Complex HTML)

If your Summernote content has nested tags, formatting quirks, or more complex HTML, Thymeleaf's basic stripTags might not be enough. Using a library like Jsoup to parse and extract text is far more reliable.

First, create a simple utility class in your Java code:

import org.jsoup.Jsoup;

public class HtmlProcessingUtils {
    public static String convertHtmlToPlainText(String htmlContent) {
        if (htmlContent == null || htmlContent.isEmpty()) {
            return "";
        }
        // Jsoup parses the HTML and extracts clean, well-formatted plain text
        return Jsoup.parse(htmlContent).text();
    }
}

Register this bean in your Spring context (if you're using Spring), then call it directly in your Thymeleaf template:

<div th:title="${@htmlProcessingUtils.convertHtmlToPlainText(summernoteContent)}">
  Hover over me
</div>

Jsoup handles edge cases like nested tags, broken HTML, or hidden elements much better than the built-in strip method.

Just a quick reminder: Even if you tried to put raw HTML into the title attribute, browsers would display the tags as plain text (e.g., <b style='color:#CCC'>Test</b> instead of a gray bold "Test"). So converting to plain text is the only way to get the expected user experience.

内容的提问来源于stack exchange,提问作者Confuser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:09