我正在使用 Timeleaf 编写一个 Java Spring 项目。
这是我的
MainController
:
package com.amo.lab2.controller;
import com.amo.lab2.utils.CountingSort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MainController {
@GetMapping("/form")
public String form() {
return "form";
}
@PostMapping("/processSorting")
public String doSorting(@RequestParam("array") String array, Model model) {
// some logic
CountingSort countingSort = new CountingSort(intArray);
model.addAttribute("countingSort", countingSort);
return "chart";
}
}
这是
chart.html
的一部分:
<body>
<div style="width: 80%; margin: auto;">
<canvas id="myChart"></canvas>
</div>
<script>
var xValues = *there should be value countingSort.xValues*;
var yValues = *there should be value countingSort.yValues*;
var ctx = document.getElementById('myChart').getContext('2d');
// creating a dependency graph
</script>
</body>
有什么方法可以分配变量
xValues
和 yValues
我通过模型传递的 countingSort
的值吗?
我试着写
var xValues = [${countingSort.xValues}];
var yValues = [${countingSort.yValues}];
但显然没有效果。我什至不知道如何去做。
使用 Thymeleaf,您必须做一些额外的事情才能从脚本部分访问模型变量。
Thymeleaf 3 之前的版本:
<script th:inline="javascript">
/*<![CDATA[*/
var xValues = /*[[${countingSort.xValues}]]*/;
var yValues = /*[[${countingSort.yValues}]]*/;
/*]]>*/
</script>
如果您使用的是 Thymeleaf 3:
<script th:inline="javascript">
var xValues = [[${countingSort.yValues}]];
</script>
请参阅此了解更多详细信息。 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlined