Object to JSON serialization inside thymeleaf template

15,451

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>
Share:
15,451
mannysz
Author by

mannysz

Updated on June 27, 2022

Comments

  • mannysz
    mannysz almost 2 years

    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>