0

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?

2
  • i think you must write the variable randomString within the CDATA section just before your username variable. Commented Jun 20, 2018 at 11:06
  • There is no harm in initializing variable inside the [CDATA] tag. :) Commented Jun 20, 2018 at 12:52

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

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.