thymeleaf 中是否有办法从上下文中输出对象的 json。我可以在 Controller 内完成,但真的不想这样做。
Controller :
@RequestMapping("/{projectId}/edit")
public String editProject(Model model, @PathVariable Long projectId) {
Project project = projectRepo.findOne(projectId);
// Below line works, but I want to put the object to the model
// model.addAttribute("project", new ObjectMapper().writeValueAsString(project));
model.addAttribute("project", project);
return "project/edit";
}
部分模板:
<script>
var app = new Vue({
el: '#app',
data: {
project: [(${project})]
}
});
</script>
请您参考如下方法:
Thymeleaf 开箱即用,我认为您只需要添加 th:inline="javascript"
。
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart
<script th:inline="javascript">
var app = new Vue({
el: '#app',
data: {
project: /*[[${project}]]*/ {}
}
});
</script>