将Thymleaf变量传递给Javascript函数

时间:2020-05-17 06:57:49

标签: javascript spring-boot thymeleaf

我想将Thymleaf变量传递给javascript函数。我的Thymleaf部分就是这样

<a class="cat-title"  th:onclick="|fetchProduct('${category.categoryId}','${businessId}')|">
                                    <p th:text="${category.name}"></a>

我的JavaScript代码就是这样

   function fetchProduct(businessId,categoryId) {

    var productUrl = '/webstore/business/' + businessId + '/category/' + categoryId + '/products';
    ............
    ............
    }   

但是当我加载页面时出现此错误

由以下原因引起:org.thymeleaf.exceptions.TemplateProcessingException:仅 在此允许返回数字或布尔值的变量表达式 上下文,在此上下文中不信任任何其他数据类型 表达式,包括字符串或任何其他可能是 呈现为文本文字。

此错误的原因是什么?

2 个答案:

答案 0 :(得分:1)

尝试

<a class="cat-title"  th:onclick="fetchProduct([[${category.categoryId}]], [[${businessId}]]);">
    <p th:text="${category.name}"></a>

答案 1 :(得分:0)

我想原因可能是该错误https://github.com/thymeleaf/thymeleaf/issues/707前一段时间报告的。

您可以尝试内联JS变量:

<a class="cat-title" 
   th:onclick="'javascript:fetchProduct(\'' + [[${category.categoryId}]] + '\', \'' + [[${businessId}]] + '\');'">
       <p th:text="${category.name}">
</a>

还有另一种方法也应该起作用(尚未在编辑器中检查它!),但它看起来要好一些,因为您不需要连接字符串和太多\':)

<a class="cat-title" 
    th:dataCatId="${category.categoryId}"
    th:dataBizId="${businessId}" 
    th:onclick="javascript:fetchProduct(this.getAttribute('dataCatId'), this.getAttribute('dataBizId'));">
        <p th:text="${category.name}">
</a>