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

如何让Thymeleaf与Hyperscript实现动态ID交互?

问题:Thymeleaf变量无法在Hyperscript的_属性中解析

我用Thymeleaf遍历集合生成HTML,通过th:id="'new-card-form-' + ${board.id}"能正常生成带UUID的动态ID,但在Hyperscript的_属性中,${board.id}被当作字面量字符串,无法被正确替换为实际ID。示例代码如下:

<card-form class="hidden" th:id="'new-card-form-' + ${board.id}">
    <form action="#" class="flex flex-col gap-2">
        <textarea class="textarea" placeholder="Enter title..."></textarea>
        <div class="w-full">
            <button class="bg-sky-700 px-2 py-1 rounded-lg font-bold hover:bg-sky-600 active:scale-95"
                    hx-post="/boards">Save Card</button>
            <button class="bg-gray-600 px-2 py-1 rounded-lg hover:bg-gray-700 active:scale-95"
                    _="on click hide #new-card-form-${board.id} then show #board-footer-${board.id}">Cancel</button>
        </div>
    </form>
</card-form>

解决方案

方法一:用th:attr属性构建Hyperscript内容

Thymeleaf默认不会解析普通属性内的变量表达式,用th:attr可以强制Thymeleaf解析整个属性值:

<button class="bg-gray-600 px-2 py-1 rounded-lg hover:bg-gray-700 active:scale-95"
        th:attr='_="on click hide #new-card-form-${board.id} then show #board-footer-${board.id}"'>
    Cancel
</button>

注意用单引号包裹_的内容,避免和内部双引号冲突,Thymeleaf会自动替换其中的${board.id}为实际UUID。

方法二:使用Thymeleaf内联表达式直接插入变量

用[[${board.id}]]内联语法直接在_属性值中插入动态变量:

<button class="bg-gray-600 px-2 py-1 rounded-lg hover:bg-gray-700 active:scale-95"
        _="on click hide #new-card-form-[[${board.id}]] then show #board-footer-[[${board.id}]]">
    Cancel
</button>

这种方式更直观,Thymeleaf会直接把[[${board.id}]]替换为对应的UUID值。

两种方法最终都会生成正确的Hyperscript代码,比如当board.id为123e4567-e89b-12d3-a456-426614174000时,输出的属性会是:

_="on click hide #new-card-form-123e4567-e89b-12d3-a456-426614174000 then show #board-footer-123e4567-e89b-12d3-a456-426614174000"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:32:05