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

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

本文介绍了Thymeleaf外部javascript文件与html文件共享模块属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

有两个控制器-html控制器和javascript控制器,html控制器提供用于呈现html模板的模块属性,javascript控制器假定为javascript提供模块属性.但是,javascript还需要使用html控制器提供的模块属性.如果我将javascript移到了html文件中(内联javascript);在html文件中,类似于:

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>

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

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.

推荐答案

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

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>

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

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.

更新:-

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

然后在此行下面,将您的链接放置到您的外部JS文件中.

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

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

这篇关于Thymeleaf外部javascript文件与html文件共享模块属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:40