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
相关产品推荐
相关产品推荐

