Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object to JSON serialization inside thymeleaf template

Is there a way in thymeleaf to output json of an object from the context. I can do it inside the controller but don't really want to.

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";
}

Partial Template:

<script>
    var app = new Vue({
        el: '#app',
        data: {
            project: [(${project})]
        }
    });
</script>
like image 859
Bahadır Yağan Avatar asked Nov 29 '16 19:11

Bahadır Yağan


1 Answers

Thymeleaf does this out of the box, I think you just need to add 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>
like image 57
Metroids Avatar answered Oct 21 '22 21:10

Metroids