Bas
Bas

Reputation: 2210

Thymeleaf inline javascript expression with variable

I'm using Spring Boot with Thymeleaf, and know I can use variables from my controller on the following way in javascript:

<script th:inline="javascript">

/*<![CDATA[*/
var username = [[${#authentication.principal.person.isSubscribedTo("random string")}]];
/*]]>*/

</script>

Now I tried to use a local variable outside the CDATA comment like this. I expected I could use that in the method.

var randomString = "can i use this?";
/*<![CDATA[*/
var username = [[${#authentication.principal.person.isSubscribedTo(randomString)}]];
/*]]>*/

This does not work and I can't test this because my debugger won't get it the method and is not giving back any errors.

How can I use a local javascript variable in a thymeleaf javascript expression?

Upvotes: 0

Views: 1486

Answers (1)

user65839
user65839

Reputation:

You're showing a bit of confusion about what's happening when and where.

First, the server uses Thymeleaf to generate the HTML and dynamic Javascript for a page. In this process, as you've said Thymeleaf can call into your Spring beans as it's running on the server.

Then, once the HTML & dynamic Javascript is sent to the browser, it runs the Javascript all client-side.

The only real approaches are:

  1. Generate that randomString on the server side as well, within Thymeleaf or in the model accessible to Thymeleaf.
  2. If you need to generate that string on the client side, have the Javascript make a separate HTTP request ("AJAX") call with that information to the server, and then do something reasonable with the response. That is to say, once the Javascript is sent to the browser, if you need to make more round trips to the server it's on the Javascript to ensure that it happens, as Thymeleaf's role in the page is done.

Upvotes: 1

Related Questions