본문 바로가기

Framework/Spring Boot

Thymeleaf model attribute로 html 동적 업데이트(리랜더링)

Tip thymeleaf model attribute로 html 동적 업데이트

 

SpringBoot 에 Thymeleaf를 사용한 프로젝트에서 backend 작업 후 업데이트된 데이터를 model attribute 로 받아 html의 특정 영역을 리랜더링(re-rendering) 하고 싶을 때가 있죠.

 

예를 들면 동적으로 업데이트될 수 있는 detail 영역 이라던지...

<div th:text="${msg}"></div>
<table>
	<tbody>
    	<tr>
        	<th>이름</th>
            <td th:text="${detail.name}"></td>
        </tr>
        <tr>
        	<th>지역</th>
            <td th:text="${detail.region}"></td>
        </tr>
        <tr>
        	<th>관심사</th>
            <td th:text="${detail.interest}"></td>
        </tr>
    </tbody>
</table>

 


 

1. 업데이트할 html 요소에 id값 부여하기

동적 업데이트하여 리랜더링할 요소에 unique id를 부여합니다.

<!-- test.html -->
<div id="divId">
	<!-- 초기 model attribute "msg" 값 설정됨 -->
	<span th:text="${msg}"></span>
</div>

 

2. controller 구현

controller에서 로직 완료 후 [해당 view 명] :: [업데이트할 html 요소의 ID] 로 return합니다.

return "test :: #divId";
@GetMapping("ajax/refresh")
public String refresh(@RequestParam String elId, Model model) {
	// TODO - backend 처리
	// model attribute "msg" 값 설정
	model.addattribute("msg", "re-render message!");
	return "test :: #" + elId; // view + re-rendering 할 element ID
}

 

3. 업데이트할 controller 호출 및 화면 업데이트

controller는 ajax 등의 비동기로 호출하고, 반환된 데이터로 html element 를 업데이트합니다.

$.ajax({
	url : "ajax/refresh",
	type : "get",
	dataType : "text",
	data : {
		elId : "divId", // re-rendering 대상 element ID
	},
	success : function(result) {
		$("#divId").replaceWith(result);
	},
});

 

728x90

'Framework > Spring Boot' 카테고리의 다른 글

Thymeleaf message.properties 동적으로 값 넣기  (1) 2024.04.12