簡體   English   中英

Spring和Thymeleaf:如何將javascript移動到單獨的.js文件中

[英]Spring and Thymeleaf: How to move javascript to a separate .js file

例:

這有效

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
    <button th:onclick="'javascript:sayHello(\'hello\')'">Say Hello</button>
</body>

<script>
    function sayHello(text) {
        alert(text);
    }
</script>
</html>

但是,如果我將js移動到同一文件夾中的文件hello.js,則腳本無效。

我嘗試嵌入這樣的:

<script type="text/javascript" th:src="@{hello.js}"></script>

像這樣:

<script type="text/javascript" src="hello.js"></script>

我做錯了什么?

假設您使用Spring Boot的默認配置,您應該在src/main/resources/templates/包含您的thymeleaf文件,因此您應該將javascript文件放入:

/src/main/resources/static

說明 :您的構建工具(Maven或Gradle)將復制應用程序類路徑中/src/main/resources/所有內容,並且如Spring Boot的文檔中所述,類路徑中名為/static的目錄中的所有內容都將是作為靜態內容。


這個目錄也可以,但不鼓勵:

/src/main/webapp/

如果您的應用程序將打包為jar,請不要使用src / main / webapp目錄。 雖然這個目錄是一個通用標准,但它只適用於war包裝,如果你生成一個jar,它將被大多數構建工具默默忽略。

根據Spring Boot文檔,靜態資源是從/ static,/ public或類路徑提供的。

http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content

還簡要提到了如何重新加載靜態內容和模板文件。

http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#howto-reload-static-content

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM