jQuery 플러그인 중 문자열 태그를 영역에 Append 할때 유용한 플러그인
출처 : https://github.com/BorisMoore/jquery-tmpl
- 출처에는 사용법에 대한 예시가 상세히 나와 있습니다.
GitHub - BorisMoore/jquery-tmpl: The original official jQuery Templates plugin. This project was maintained by the jQuery team a
The original official jQuery Templates plugin. This project was maintained by the jQuery team as an official jQuery plugin. It is no longer in active development, and has been superseded by JsRende...
github.com
아래 예시에 대한 HTML 다운로드
- 아래 코드 블럭에서 1은 문자열을 더해서 태그를 만드는 방식이고, 2번은 tmpl 을 사용한 방식
1. 기존 방식 (예시)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script>
$(function() {
// 템플릿 선언
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function (data) {
// ASIS - 문자열 append 방식
var html = '';
for (let i = 0; i < data.length; i++) {
html += '<tr><td>' + data[i].id + '</td><td>' + data[i].title + '</td><td>' + data[i].body + '</td></tr>';
}
$('#tbody').html(html);
}
});
});
</script>
</head>
<body>
<div class="col-md-8">
<table class="table table-dark">
<thead>
<tr>
<th>ID</th>
<th>타이틀</th>
<th>바디</th>
</tr>
</thead>
<!-- TBODY 에 ajax 로 호출받은 데이터를 문자열로 붙이기-->
<tbody id="tbody"></tbody>
</table>
</div>
</body>
</html>
2. tmpl 사용 방식
- 아래 코드를 jsfiddle 의 html 영역에 복사하고 run 버튼을 클릭하여 테스트 할 수 있습니다.
https://jsfiddle.net/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script>
$(function() {
// 템플릿 선언
$.template("tbodyTemplate", "<tr><td>${id}</td><td>${title}</td><td>${body}</td></tr>");
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function (data) {
// 영역에 Append
$.tmpl("tbodyTemplate", data).appendTo("#tbody");
}
});
});
</script>
</head>
<body>
<div class="col-md-8">
<table class="table table-dark">
<thead>
<tr>
<th>ID</th>
<th>타이틀</th>
<th>바디</th>
</tr>
</thead>
<!-- TBODY 에 ajax 로 호출받은 데이터를 문자열로 붙이기-->
<tbody id="tbody"></tbody>
</table>
</div>
</body>
</html>
실행 결과
'Web > JS & jQuery' 카테고리의 다른 글
유효성 검사 (1) | 2024.09.03 |
---|---|
jQuery-Confirm 플러그인 (1) | 2024.09.01 |
String.Format, String.IsNullOrEmpty, String.IsNullOrWhiteSpace (0) | 2024.08.30 |
FAKE Ajax JSON 데이터가 필요할 때 jsonplaceholder (0) | 2024.08.30 |
JavaScript 에서 StringBuilder 를 사용해 보자 (0) | 2024.08.29 |