Can I use th:inline for a separate javascript file?

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Can I use th:inline for a separate javascript file?

eastmaels
Hello,

Is it possible to use th:inline for a separate javascript file?

Basically, what I want to do is to access thymeleaf variables in my javascript resource.

For example:

home.html
<script type="text/javascript" th:inline="javascript" src="./resources/home.js" th:src="@{/resources/home.js}"></script>
home.js
$(document).ready(function(){
  var postUrl = /*[[${myVar.name}]]*/ "./vicinity_map.html";
});

Thanks!
Reply | Threaded
Open this post in threaded view
|

Re: Can I use th:inline for a separate javascript file?

eiryu
I try this, but it is NOT possible...
Reply | Threaded
Open this post in threaded view
|

Re: Can I use th:inline for a separate javascript file?

Zemi
Administrator
In reply to this post by eastmaels
No, I'm afraid that it is not possible.

However, you could apply Thymeleaf to the javascript file separatedly, using the same techique as we use to send plain text emails.

Look at the method sendSimpleMail() at
   https://github.com/thymeleaf/thymeleafexamples-springmail/blob/master/src/main/java/thymeleafexamples/springmail/service/EmailService.java

(feel free to download the full example).

Reply | Threaded
Open this post in threaded view
|

Re: Can I use th:inline for a separate javascript file?

hgrimm
In reply to this post by eastmaels

One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)

  • Create a controller @RequestMapping(value = "/mydynamic.js", method = RequestMethod.GET)
  • In your controller function, create a string representing the javascript file of URL "constants":
    		var BASE_APP='/abc/';
    		var VICINITYMAP = 'vicinity_map.html';
    		...
          
  • Wrap the string with an HttpEntity and return it:
    		HttpHeaders responseHeaders = new HttpHeaders();
    		responseHeaders.set("Content-Type", "application/javascript");
    		HttpEntity<String> httpEntity = new HttpEntity<String>(script, responseHeaders);
    		return httpEntity;
          
  • Use the "constants" in your javascript files:
    		var postUrl = BASE_APP + VICINITYMAP;
          
Reply | Threaded
Open this post in threaded view
|

Re: Can I use th:inline for a separate javascript file?

eastmaels
I understand.
In order to use thymeleaf for my URLs, will most likely pass the url as parameter to the JS function.

Thanks everybody for your help!