appzone_oto
appzone_oto

Reputation: 333

ThymeLeaf: How can i pass a model attribute sent from my server to JS from Thymeleaf

I am send Sending a list from server to thymeleaf through model attribute

friendsOnlineModel.setFriendsOnline(defaultFriendRequestService.getFriendsOnline(user) == null ? Collections.EMPTY_LIST : defaultFriendRequestService.getFriendsOnline(user));

    chatModel.setChats(defaultChatService.getUnreadChats() == null ? Collections.EMPTY_LIST : defaultChatService.getUnreadChats());

    model.addAttribute("friends_online", friendsOnlineModel);

    model.addAttribute("chats", chatModel);

I dont want to display them straight in an "li" tag, but rather pass it to a js function which displays them. Is it possible?

Upvotes: 0

Views: 799

Answers (1)

Metroids
Metroids

Reputation: 20477

There are a couple ways you can do this. You could use JavaScript inlining, and add the data directly into your page. Similar to the example:

<script th:inline="javascript">
    var fiendsOnline = [[${friends_online}]];
    var chats = [[${chats}]];
</script>

Then you can deal with them in javascript however you want.

Or, instead of putting these attributes on the model, you can add them to a different controller method annotated with @ResponseBody. Then you call that method using ajax, and Spring will return your object as JSON.

Upvotes: 4

Related Questions