[Spring Boot] Thymeleaf onclick 설정

2022. 4. 19. 20:01Web/Spring

프로젝트 중에서 글을 좋아요 누르는 기능 구현 중에 button에 onclick을 달아서 실행하고자 하였다.

thymeleaf를 통해 view 화면을 구성하고 있는데 th:onclick으로 구현하려고 했지만 실행해본 결과 구현이 되지 않았다. 

 

버튼을 통해 postMapping으로 좋아요 수를 하나씩 증가시키는 기능으로 구현한 HTML은 다음과 같다.

<div>
	<img th:src="|/upload/${post.uploadFile.storeFileName}|" width="600" height="600">
</div>
<div>
	<button id="likes" th:onclick="putLikes(${post.id})">좋아요</button>
</div>

putLikes라는 함수를 작성하고 변수를 넣어 기존 post id를 FK로 참조하는 Like 객체를 새로 형성하는 방법 이었다.

그런데 사실 onclick이 먹히지 않아서 stackOverflow를 검색해봤는데 비슷한 문제로 해결하고자 하는 질문이 있었다. 

 

https://stackoverflow.com/questions/32650536/using-thymeleaf-variable-in-onclick-attribute

 

Using thymeleaf variable in onclick attribute

In my current spring-boot project, I have one view with this html code: <button type="button" class="btn btn-primary" onclick="upload()" th:utext="#{modal.save}"></button> in the oncl...

stackoverflow.com

보니까 thymeleaf 3.0.10 부터는 onclick을 더 이상 지원하지 않으며 속성 attr에 onclick을 넣어서 구현하는 방식이었다.

이렇게 th:attr ="onclick=|[함수이름]('${변수}')|"로 넣으면 onclick으로 인식하여 작동이 된다고 한다.

그래서 다시 바꿔서 써넣어봤다. 

<div>
    <button id="likes" th:attr="onclick=|putLikes('${post.id}')|">좋아요</button>
</div>

결과적으로 좋아요 갯수가 버튼을 누를 때 마다 하나씩 올라간 것을 확인할 수 있었다.

이제 fetch join으로 size() 대신 갯수를 가져오는 걸 구현해봐야 겠다.