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

Thymeleaf external javascript file shares the module attributes with html file

假设您有一个 HTML5 模板文件,其中包含一个外部 javascript 文件。例如:

<!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>

有两个控制器——html控制器和javascript控制器,html控制器提供模块属性渲染html模板,javascript控制器假设为 javascript 提供模块属性。但是 javascript 还需要使用 html 控制器提供的模块属性。如果我将 javascript 移动到 html 文件中(内联 javascript);在 html 文件中,类似于:

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

没有问题,但如果我将脚本移出到单独的外部 javascript 文件,外部 javascript 如何访问 html 控制器提供的模块属性?有没有办法 javascript 控制器与 html 控制器交换模块属性? 我用 Spring 启动 1.5.10,Thymeleaf 3.0.9。

您可以在外部 js 文件中使用在 <script></script> 标记(内联)内声明的变量。只需在 html

中引用外部 js 文件
<script>
var showtext = "[[${readingListObject.course.Id}]]";
</script>

然后在您的外部脚本中您可以访问 showtext 变量。因此,您可以在 html 中使用内联 js 仅传递属性,然后您可以使用变量在外部 js 中执行逻辑。

更新:-

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

然后就在这一行下方,将 link 放入外部 JS 文件。

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