Tymeleaf의 th:onclick 사용법

Jung-Kwon Lee·2023년 7월 27일

Thymeleaf

목록 보기
1/1

타임리프를 이용해 onclick 이벤트 걸 때, 사용법에 대해서 참고하고자 작성한다.

1. location.href 경로 이동

<button th:text"예시" th:onclick="location.href='@{/example/}'|"></button>
<!-- 결과 : /example/ -->

경로 뒤에 id값을 붙이고 싶으면 다음과 같이 작성하면 된다.

<button th:text="예시" th:onclick="|location.href='@{/example/}| + ${example.id} + |'|"></button>
<!-- 결과 : /example/1 -->

2. location.href 경로 이동시에 requestParam으로 파라미터 넘기고 싶을 때

<button th:text"예시" th:onclick="|location.href='@{/example(exampleCode=${item.exampleCode})}'|"></button>
<!-- 결과 : /example?exampleCode=[item.exampleCode 값] -->

단일 파라미터일 경우 위의 예시와 같이 작성하면 된다. 파라미터가 여러개일 경우 (exampleCode=${item.exampleCode}, exampleCode1=${item.exampleCode1})
이와 같이 파라미터 뒤에 쉼표를 붙이고 key=value 형태로 작성하면 된다.

타임리프 리터럴:

타임리프에서 문자를 입력할 때 작은따옴표로 감싸거나 파이프로 감싸야한다.
(공백이 없으면 사용하지 않아도 되지만 사용하는 것이 좋다.)

<!-- hello world 출력하는 3가지 방법 -->
<span th:text="'hello'+'world'"></span>
<span th:text="'hello world'"></span>
<span th:text="|hello world|"></span>

Reference :
[Thymeleaf] 타임리프 th:onclick 사용하기 - by 강은zeo (https://zoetechlog.tistory.com/112)

0개의 댓글