Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Example:

This works

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

But, if I move js to the file hello.js in the same folder, script is not working.

I tried embed like this:

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

And like this:

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

What I'm doing wrong?

like image 690
Andrew Avatar asked Dec 30 '14 16:12

Andrew


2 Answers

Assuming you are using default configurations from Spring Boot you should have your thymeleaf file in src/main/resources/templates/ so you should put the javascript file in:

/src/main/resources/static

Explanation: your build tool (Maven or Gradle) will copy all the content from /src/main/resources/ in the application classpath and, as written in Spring Boot's docs, all the content from a directory called /static in the classpath will be served as static content.


This directory could works also, but it is discouraged:

/src/main/webapp/

Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.

like image 119
Andrea Avatar answered Oct 11 '22 23:10

Andrea


According to the Spring Boot documentation, static resources are served from /static, /public or off the classpath.

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

There is also a brief mention of how to reload your static content and template files.

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

like image 37
David Avatar answered Oct 12 '22 01:10

David