一、概述
在本教程中,我们将在Thymeleaf 模板中调用JavaScript函数。
我们将从设置依赖项开始。然后,我们将添加我们的Spring 控制器和Thymeleaf 模板。最后,我们将展示根据输入调用JavaScript 函数的方法。
2. 设置
为了在我们的应用程序中使用Thymeleaf,让我们将Thymeleaf Spring 5依赖添加到我们的Maven 配置中:
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.11.RELEASE</version> </dependency>
然后,让我们根据Student
模型将其添加到Spring 控制器中:
@Controller public class FunctionCallController { @RequestMapping(value = "/function-call", method = RequestMethod.GET) public String getExampleHTML(Model model) { model.addAttribute("totalStudents", StudentUtils.buildStudents().size()); model.addAttribute("student", StudentUtils.buildStudents().get(0)); return "functionCall.html"; } }
最后,我们将这两个JavaScript 函数添加到src/main/webapp/WEB-INF/views
下的functionCall.html
模板中:
<script th:inline="javascript"> function greetWorld() { alert("hello world") } function salute(name) { alert("hello: " + name) } </script>
我们将在下面的下一节中使用这两个函数来说明我们的示例。
如果有任何问题,我们可以随时检查如何将JavaScript 添加到Thymeleaf。
3. 在Thymeleaf 中调用JavaScript 函数
3.1。使用没有输入的函数
下面是我们如何调用上面的greetWorld
函数:
<button th:onclick="greetWorld()">using no variable</button>
它适用于任何自定义或内置JavaScript 函数。
3.2.使用具有静态输入的函数
如果我们在JavaScript 函数中不需要任何动态变量,可以这样调用它:
<button th:onclick="'alert(\'static variable used here.\');'">using static variable</button>
这会转义单引号并且不需要SpringEL。
3.3.使用具有动态输入的函数
使用变量调用JavaScript 函数有四种方式。
插入变量的第一种方法是使用内联变量:
<button th:onclick="'alert(\'There are exactly ' + ${totalStudents} + ' students\');'">using inline dynamic variable</button>
另一种选择是调用javascript:function
:
<button th:onclick="'javascript:alert(\'There are exactly ' + ${totalStudents} + ' students\');'">using javascript:function</button>
第三种方式是使用数据属性:
<button th:data-name="${student.name}" th:onclick="salute(this.getAttribute('data-name'))">using data attribute</button>
当调用JavaScript 事件(如onClick
和onLoad
)时,此方法会派上用场。
最后,我们可以使用双方括号语法调用我们的salute
函数:
<button th:onclick="salute([[${student.name}]])">using double brackets</button>
双方括号之间的表达式被认为是Thymeleaf 中的内联表达式。这就是为什么我们可以使用在th:text
属性中也有效的任何类型的表达式。
4。结论
在本教程中,我们学习了如何在Thymeleaf 模板中调用JavaScript 函数。我们首先设置我们的依赖项。然后,我们构建了控制器和模板。最后,我们探索了在Thymeleaf 中调用任何JavaScript 函数的方法。
0 评论