Strategy for using model attributes in external javascript files

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

Strategy for using model attributes in external javascript files

Ryan F
In the current project I am working on now, our development team is attempting to utilize the Eclipse IDE JSDT (JavaScript Development Tools) to provide as much JavaScript linking functionality as possible in our Spring MVC web app. Unfortunately, it the plugin fails at linking a global variable defined in inline JavaScript script tags in HTML pages to the same variable used in external JavaScript files.

However, in order to retrieve model attributes within the JavaScript tags using Thymeleaf, it all has to be inline. For example, this is how I've always done it:

<script th:inline="javascript"> /*<![CDATA[*/ var data = /*[[${data}]]*/ {}; /*]]>*/ </script>
<script th:src="@{/resources/js/a_file_that_will_use_data.js}"></script>

While Thymeleaf generates the variable correctly, the JSDT plugin will not identify data variable initialized here in this script tag in the external "a_file_that_will_use_data.js" file because it is initialized in the containing HTML file.

Is there a way for me to have my cake and eat it too? Ideally, I would like to be able to incorporate my controller defined model attributes in external JavaScript files, and have no inline JavaScript. So far, I see my possibilities as:

1) Continue doing the way I outlined above and abandon the plugin
2) Writing all JavaScript functionality inline (ew)
3) ???

Any advice?
Reply | Threaded
Open this post in threaded view
|

Re: Strategy for using model attributes in external javascript files

blandger
<script th:src="@{/resources/js/a_file_that_will_use_data.js}" src="/resources/js/a_file_that_will_use_data.js"></script>
???
Reply | Threaded
Open this post in threaded view
|

Re: Strategy for using model attributes in external javascript files

Zemi
Administrator
In reply to this post by Ryan F
You could have an initialization block for static resources and make Thymeleaf remove it at runtime.

    < script th:remove="all" >
        var data = {};
    < /script >