0

I'm wondering if there's a way to access a JavaScript object from within thymeleaf's inline syntax.

I'm trying to build a URL using the [[@{}]] syntax in JavaScript. However, inside of the URL, I need to get access to a JS variable.

Here's the code:

var fieldPathStr = /*[[@{{lessonId}/questions/{questionId}(lessonId=${lesson.id}, questionId=question.id)}]]*/"1/questions/2";

Specifically, it's the question.id that is the JS variable, but it (obviously) just creates the final URL as:

1/questions/question.id

Is there a way to structure this assignment statement so that I can get the actual value of question.id and have it evaluate it properly?

1 Answer 1

2

You can extract values like this:

var lessonId = [[${lesson.id}]];
var questionId = [[${question.id}]];

but I am not sure that it is a way to go. If you are working with the lists, you would need to extract them in js which means twice the work on the machine side... There is a way to do it, but probably little different than what you thought! An example of how I managed my popup box to confirm removal of item from the list:

<script th:inline="javascript">
    function deleteObject(id) {
        bootbox.confirm([[#{msg.ask}]], function(result) {
            if (result) {
                var url = /*[[ @{'/admin/vozila/izbrisi?vin='} ]]*/ "genericUrl";
                url = url+id;
                document.location = url;
            }
        }); 
    };
</script>

Once this is done, all you need is to call it and pass the object id:

<a class="btn btn-default btn-sm" href="#" th:onclick="'javascript:deleteObject(\'' + ${vozilo.vin} + '\');'"><i class="glyphicon glyphicon-remove"></i><span th:text="#{rad.obr}">Radnja - izbrisi</span></a>

So you are not getting thymeleaf rendered inside js, but you pass the values to the function when called. I guess in your case it would look something like this:

<script th:inline="javascript">
function callLink(lessonID, questionID){
var fieldPathStr = lessonID+/*[[@{'/questions/'}]]*/"1/questions/2";
var finalStr = lessonID+fieldPathStr+questionID;
};
</script>

where questionID, and lessonID should look like this:

<a href="#" th:onclick="'javascript:callLink(\'' + ${lesson.id} + '\', \'' + ${question.id} + '\');'"></a>

Hope this works for you?

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah that will probably work. I'm not sure why I didn't think to just populate the ID afterwards, pretty easy fix... silly me
We've all been there! :D

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.