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

Thymeleaf转义HTML字符致Plausible API无法正确接收金额问题

Thymeleaf渲染onclick属性时HTML转义导致Plausible API无法正确获取金额值

问题场景

在通过Plausible API跟踪营收事件时,遇到Thymeleaf自动HTML转义的问题:使用[[${result.price}]]渲染价格到onclick事件的参数中时,最终生成的代码里amount值变成了quot;1234quot;,导致API无法正确解析金额;但直接写死amount: 1234时,API就能正常存储数据。

原Thymeleaf代码

<div class="product-card" th:each="result : ${searchResults}">
    <div class="product-image">
        
        <a th:href="@{${result.url}}" target="_blank" rel="noopener noreferrer"><img
                class="product-thumb plausible-event-name=product+click"
                th:onclick="window.plausible('product click', {revenue: {currency: 'SEK', amount: [[${result.price}]] }})"
            th:src="${result.imageUrl}" onerror="this.src='Product-Image-Coming-Soon.jpg'" alt=""></a>

    </div>
</div>

渲染后的错误HTML

<img class="product-thumb plausible-event-name=product+click" onclick="window.plausible('product click', {revenue: {currency: 'SEK', amount: quot;1234quot; }})" src="https://cdn-1.xxx.com/UMPROhsfQv4SWki4SpOhY9O6hydA9CI09YTchmT2mbQ.jpeg" onerror="this.src='Product-Image-Coming-Soon.jpg'" alt="">

解决方案

方法1:使用Thymeleaf无转义表达式 [(...)]

Thymeleaf的[(...)]表达式会直接输出原始值,不进行HTML转义,适合在JavaScript上下文或属性中使用:

<div class="product-card" th:each="result : ${searchResults}">
    <div class="product-image">
        
        <a th:href="@{${result.url}}" target="_blank" rel="noopener noreferrer"><img
                class="product-thumb plausible-event-name=product+click"
                th:onclick="window.plausible('product click', {revenue: {currency: 'SEK', amount: [(${result.price})] }})"
            th:src="${result.imageUrl}" onerror="this.src='Product-Image-Coming-Soon.jpg'" alt=""></a>

    </div>
</div>

方法2:使用th:attr构建onclick属性

通过th:attr手动拼接onclick属性内容,也能避免自动转义问题:

<div class="product-card" th:each="result : ${searchResults}">
    <div class="product-image">
        
        <a th:href="@{${result.url}}" target="_blank" rel="noopener noreferrer"><img
                class="product-thumb plausible-event-name=product+click"
                th:attr="onclick=|window.plausible('product click', {revenue: {currency: 'SEK', amount: ${result.price} }})|"
                th:src="${result.imageUrl}" onerror="this.src='Product-Image-Coming-Soon.jpg'" alt=""></a>

    </div>
</div>

两种方法都会渲染出正确的JavaScript代码,让amount值以数字形式传递给Plausible API:

<img class="product-thumb plausible-event-name=product+click" onclick="window.plausible('product click', {revenue: {currency: 'SEK', amount: 1234 }})" src="https://cdn-1.xxx.com/UMPROhsfQv4SWki4SpOhY9O6hydA9CI09YTchmT2mbQ.jpeg" onerror="this.src='Product-Image-Coming-Soon.jpg'" alt="">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:33:22