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

Thymeleaf渲染代码示例块:无需手动转义HTML标签实现纯文本展示

问题描述

我正在构建自定义内部开发者指南/组件库,当前使用的Thymeleaf模板代码如下:

<!DOCTYPE html>
<html
  xmlns:th="http://www.thymeleaf.org"
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
  layout:decorate="~{layout-dev}"
>
  <head>
    <title>Dev | Buttons | Solid</title>
  </head>
  <body>
    <div layout:fragment="content">
      <th:block th:insert="~{dev/buttons/menu :: menu}"></th:block>
      <div class="space-y-2">
        <div>
          <button
            type="submit"
            class="my-css-class">
            Log in
          </button>

          <!-- Magic here -->
          <code>
            <button
              type="submit"
              class="my-css-class"
            >
              Log in
            </button>
          </code>
        </div>
      </div>
    </div>
  </body>
</html>

希望将上述按钮示例渲染为纯文本形式,无需手动将所有HTML标签转换为&lt;和&gt;,最终呈现为带语法高亮的美观代码块。

解决方案

1. 利用Thymeleaf内置工具自动转义

借助Thymeleaf的#strings.escapeXml工具方法,配合<pre><code>标签实现自动转义和格式保留:

方式A:内联代码片段

<div>
  <button type="submit" class="my-css-class">Log in</button>

  <pre><code class="html" th:utext="${#strings.escapeXml('<button type=\"submit\" class=\"my-css-class\">Log in</button>')}"></code></pre>
</div>

方式B:引用外部代码片段

把按钮代码单独存为Thymeleaf片段文件(比如dev/buttons/solid-button-code.html):

<button
  type="submit"
  class="my-css-class"
>
  Log in
</button>

然后在主模板中调用并转义:

<div>
  <button type="submit" class="my-css-class">Log in</button>

  <pre><code class="html" th:utext="${#strings.escapeXml(~{dev/buttons/solid-button-code})}"></code></pre>
</div>

2. 集成语法高亮工具实现美观效果

要达到规整的高亮样式,引入语法高亮库(比如Highlight.js):

  • 在模板头部添加依赖:
<link rel="stylesheet" href="/assets/highlight.min.css">
<script src="/assets/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
  • 给<code>标签添加语言类(比如class="html"),工具会自动识别并高亮代码。

这样既不用手动转义标签,又能得到格式整齐、带语法高亮的代码块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:32:51