본문 바로가기
개발자 전향 프로젝트

[Spring] 모달 쉽게 띄우기 + 모달에 매개변수 값 전달하기 (타임리프)

by 샘오리 2022. 9. 21.

1. 부트스트랩 5버전의 CDN  추가

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

2. 모달을 호출할 버튼을 만든다. data-target 에 모달 ID를 넣으면 모달이 호출되는 원리이다.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

3. 모달을 만든다

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        이곳에 내용을 적어주세요
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

 

4. [ 응용하기 ] 하드코딩을 하지 않는다면 변수값을 가져와야 할텐데 타임리프라는 템플릿 엔진을 사용하면서

모달 외부에서 사용한 타임리프 변수값을 가져오고 싶은데 방법을 모르겠고

제이쿼리나 자바스크립트로 어떻게 값은 가져왔는데

하필이면 동적 테이블이라 첫번 째 행의 의 값만 주구장창 나온다면? 

 

TH:ATTR을 활용한다.

 

어떻게?

 

4-1 [ 설명 ] 버튼은 아래처럼 data-target을 th:attr 안에 넣는다

th:attr="data-target=${'#모달 ID'+ 변수명}"

4-2 [ 설명 ] 모달도 아래처럼 모달 id 명과 타임리프 변수명을 th:attr로 감싸준다.

th:attr="id='모달ID'+${변수명}"

 

 

data-toggle을 이용하지 않는다면 아래와 같은 방법도 존재한다.

<button type="button" th:attr="onclick=|openModal('${comment.id}', '${comment.user_name}', '${comment.comment}' )|" class="bi bi-pencil"></button>

이게 알면 금방하고 모르면 오래걸리는 타임리프 변수 넘기기 꿀팁이다.