【问题标题】:Thymeleaf external javascript file shares the module attributes with html fileThymeleaf 外部 javascript 文件与 html 文件共享模块属性
【发布时间】:2018-09-01 01:55:40
【问题描述】:

假设您有一个 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 控制器提供的模块属性。如果我在 html 文件中移动了 javascript(内联 javascript);在 html 文件中,类似于:

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

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

【问题讨论】:

    标签: javascript html spring-boot thymeleaf external


    【解决方案1】:

    您可以在外部 js 文件中使用在 &lt;script&gt;&lt;/script&gt; 标记(内联)内声明的变量。只需在您的 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>
    

    然后在这一行下方,将您的链接放到您的外部 JS 文件。

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

    【讨论】:

    • 试过了,不行。 html文件中的内联脚本为其赋值后,外部js文件中的“showtext”未定义。谢谢。
    • 把内联脚本标签放在外部js的正上方
    • 感谢您的帮助,您能详细说明一下吗?我试过你的解决方案,不行。
    • 我目前在我的项目中使用这种方法,它工作正常。您可以尝试在关闭正文标记之前放置您的内联 JavaScript 代码和外部 JavaScript 文件吗?在&lt;/body&gt; 之前。如果这不起作用,请告诉我
    • 那么外部 JavaScript 文件不再是外部 JavaScript 文件了。它们都是内联的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多