1

I want to pass Thymleaf variable to a javascript function. My Thymleaf portion is like this

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

And my javascript code is like this

   function fetchProduct(businessId,categoryId) {

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

But when I load the page I get this error

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal.

What is the reason for this error?

1

2 Answers 2

1

try this

<a class="cat-title"  th:onclick="fetchProduct([[${category.categoryId}]], [[${businessId}]]);">
    <p th:text="${category.name}"></a>
Sign up to request clarification or add additional context in comments.

Comments

1

I guess the reason might be this bug https://github.com/thymeleaf/thymeleaf/issues/707 reported some time ago.

You can try inlining JS vars:

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

There is also another approach that should also work (haven't checked it in editor!) but it looks a bit better as you don't need to concat strings and so many \' :)

<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>

2 Comments

what does "this.getAttribute('dataCatId')" mean?
@user3692033 this in that context refers to your HTML element a and getAttribute() method is how you can get some attribute's value. developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute. I believe Thymeleaf shout generate plain HTML <a ...></a> with 2 custom attributes and they will be accessible via getAttribute() method, so you don't need to inline JS stuff and concat strings, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.