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

如何在Thymeleaf片段中转义右括号而不闭合它?

Thymeleaf片段参数特殊字符转义问题

问题场景

调用Thymeleaf的questionaire片段时,字符串中的右括号(如First 1) ...)会意外闭合片段参数,导致语法错误;字符串包含new关键词时也会出现类似解析问题。尝试过First 1\) ...、)、)搭配utext均无效。

相关代码

片段调用代码

"fragments/questionaire :: questionaire('00001_c-1',
        ${ 
            { 
            '...',
            '...', 
            'First 1) ...'
            }
        },
        ${
            { 
            '...',
            '...',
            '...' 
            }
        },'[0,2]')"

片段定义

th:fragment="questionaire(key, questions, hints, rightIndex)"

表单遍历代码

<div th:each="aquestion, iterStat : ${questions}" th:with="qid=${key}+'_q-'+${iterStat.index},name='rb-'+${key}"> 
    <div> 
        <input type="checkbox" th:name="${name}+${'_q-'+iterStat.index}" th:value="0" th:data-s="${iterStat.index}" th:id="${qid}" autocomplete="off" th:checked="${bucket.read('questionaire.'+name+'_q-'+iterStat.index)}==('' + 1)"/> 
        <label th:for="${qid}" th:text="${aquestion}"></label> 
        <input type="hidden" th:name="${name}+${'_q-'+iterStat.index}" value="0">
    </div> 
    <div class="hint" th:id="${qid+'--hint'}" th:text="${hints[iterStat.index]}"></div> 
</div> 
<p class="submitContainer"> 
    <button th:data-qvalidate="|quest${key}|" th:text="#{q.check}">Check</button> 
</p>

解决方法

1. 模型变量传递(推荐)

将含特殊字符的字符串放到后端模型中,通过变量传递给片段,避免直接在模板写字面量引发解析冲突。

后端示例:

model.addAttribute("questionList", Arrays.asList("...", "...", "First 1) ..."));
model.addAttribute("hintList", Arrays.asList("...", "...", "..."));

模板调用修改为:

"fragments/questionaire :: questionaire('00001_c-1', ${questionList}, ${hintList}, '[0,2]')"

2. 内联表达式包裹字面量

如果必须在模板中写字面量,用[[...]]内联表达式包裹含特殊字符的内容,让Thymeleaf正确解析:

"fragments/questionaire :: questionaire('00001_c-1',
        ${ 
            { 
            '...',
            '...', 
            [[First 1) ...]]
            }
        },
        ${
            { 
            '...',
            '...',
            '...' 
            }
        },'[0,2]')"

3. new关键词处理

字符串含new时,同样适用上述两种方案:要么放到模型变量,要么用内联表达式包裹(如[[new item]])。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:15:37