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:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <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="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></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:

<script>
    var showtext = "[[${readingListObject.course.Id}]]";
    console.log(showtext);
</script>

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.

Answers:

Answer

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

<script>
var showtext = "[[${readingListObject.course.Id}]]";
</script>

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.

UPDATE :-

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

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.