Bahadır Yağan
Bahadır Yağan

Reputation: 5967

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>

Upvotes: 11

Views: 19783

Answers (1)

Metroids
Metroids

Reputation: 20477

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>

Upvotes: 19

Related Questions