简体   繁体   English

Thymeleaf外部javascript文件与html文件共享模块属性

[英]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. 假设您有一个HTML5模板文件,其中包含一个外部javascript文件。 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. 有两个控制器-html控制器和javascript控制器,html控制器提供用于呈现html模板的模块属性,而javascript控制器假定为javascript提供模块属性。 However the javascript also needs to use the module attributes provided by html controller. 但是,javascript还需要使用html控制器提供的模块属性。 If I moved the javascript inside the html file(inline javascript); 如果我将javascript移到了html文件中(嵌入式javascript); in html file, something like: 在html文件中,类似于:

<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? 没问题,但是如果我将脚本移到单独的外部javascript文件中,则外部javascript如何访问html控制器提供的模块属性? Is there a way that javascript controller exchange module attributes with html controller? 有没有办法让javascript控制器与html控制器交换模块属性? I use Spring Boot 1.5.10, Thymeleaf 3.0.9. 我使用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. 您可以使用在外部js文件的<script></script>标记(内联)中声明的变量。 just refer the external js file in your html 只是在您的html中引用外部js文件

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

Then in your external script you can access the showtext variable. 然后,您可以在外部脚本中访问showtext变量。 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. 因此,您可以在html内使用内联js仅传递属性,然后可以在外部js中使用变量进行逻辑处理。

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. 然后,在此行下方,将您的链接指向您的外部JS文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM