Thymeleaf 是一个用于Web开发的服务器端Java模板引擎,它可以与Spring框架无缝集成,主要用于渲染HTML页面。在Thymeleaf模板中引入JavaScript(JS)文件是一个常见的需求,可以通过以下几种方式实现:
<script>
标签引入外部的.js文件。<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Inline JS Example</title>
</head>
<body>
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>External JS Example</title>
</head>
<body>
<script th:src="@{/js/myScript.js}"></script>
</body>
</html>
<script>
标签中的src
属性路径是否正确。通过以上方法,可以在Thymeleaf模板中有效地引入和使用JavaScript,同时解决可能遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云