Thymeleaf external javascript file shares the module attributes with html file

Let's say you have a HTML5 template file which includes an external javascript file. for example:

<html xmlns:th="">
  <title>Reading List</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <link rel="stylesheet" type="text/css" media="all"
        href="/css/style.css" th:href="@{/css/style.css}"/>
  <script src=""></script>
  <script th:src="@{|/js/selectionCreation.js?v=${#dates.createNow()}|}"></script>

There are two controllers - html controller and javascript controller, html controller provides module attributes for rendering html template, the javascript controller supposes to provide module attributes to javascript. However the javascript also needs to use the module attributes provided by html controller. If I moved the javascript inside the html file(inline javascript); in html file, something like:

    var showtext = "[[${readingListObject.course.Id}]]";

There is no problem, but if I move the script out to a separate external javascript file, how does the external javascript access the module attributes provided by the html controller? Is there a way that javascript controller exchange module attributes with html controller? I use Spring Boot 1.5.10, Thymeleaf 3.0.9.



You can use the variables that are declared inside the <script></script> tag (inline) in the external js file. just refer the external js file in your html

var showtext = "[[${readingListObject.course.Id}]]";

Then in your external script you can access the showtext variable. So you can use an inline js inside your html to only pass the attributes, then you can do your logic inside external js using the variables.


        //Your in line code here, declare var and assign your   model   attribute

Then just below this line, put your link to your external JS file.

<script th:src="source to your external JS">


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.