로메오의 블로그

jquery tmpl 본문

App & OS/ETC

jquery tmpl

romeoh 2022. 1. 21. 16:27
반응형

형식

$.tmpl( "<li>${Name}</li>", { "Name" : "John Doe" }).appendTo( "#target" );

$(template).tmpl(data).appendTo(container)

 

Basic

<!DOCTYPE html>

<html lang="ko">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title></title>
	<script src="https://code.jquery.com/jquery-latest.min.js"></script>
	<script src="https://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

	<script id="template-company" type="text/j-query-tmpl">
	    <tr>
	        <td>${name}</td>
	        <td>${product}</td>
	    <tr>
	</script>
</head>
<body>
	<table border="1">
	    <caption>Company</caption>
	    <thead>
	        <tr>
	            <th>이름</th>
	            <th>상품</th>
	        </tr>
	    </thead>
	    <tbody id="template-list">
	    </tbody>
	</table> 


	<script type="text/javascript">
		var data = [
			{name:'구글', product:'search', nation: 'USA'}, 
			{name:'삼성', product:'mobile', nation: 'Korea'},
			{name:'애플', product:'pc', nation: 'USA'},
			{name:'소니', product:'game', nation: 'Japan'}
		];
		
		$("#template-company").tmpl(data).appendTo("#template-list");
	</script>

</body>
</html>

 

Event Update

<!DOCTYPE html>

<html lang="ko">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title></title>
	<script src="https://code.jquery.com/jquery-latest.min.js"></script>
	<script src="https://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

	<script id="template-company" type="text/j-query-tmpl">
	    <tr>
	        <td>${name}</td>
	        <td>${product}</td>
	    <tr>
	</script>
</head>
<body>
	<table border="1">
	    <caption>Company</caption>
	    <thead>
	        <tr>
	            <th>이름</th>
	            <th>상품</th>
	        </tr>
	    </thead>
	    <tbody id="container-list">
	    </tbody>
	</table> 
	<button id="btnModify">수정</button>
	<button id="btnAdd">추가</button>

	<script type="text/javascript">
		var data = [
			{name:'구글', product:'search', nation: 'USA'}, 
			{name:'삼성', product:'mobile', nation: 'Korea'},
			{name:'애플', product:'pc', nation: 'USA'},
			{name:'소니', product:'game', nation: 'Japan'}
		];
		
		function renderTemplate(container, template, data) {
			$(container).empty()
			$(template).tmpl(data).appendTo(container);
		}
		renderTemplate('#container-list', '#template-company', data)
		
		$('#btnModify').on('click', function() {
			data[0].name = 'MS';
			renderTemplate('#container-list', '#template-company', data)
		})
		$('#btnAdd').on('click', function() {
			data.push({name:'화웨이', product:'5g', nation: 'China'});
			renderTemplate('#container-list', '#template-company', data)
		})
	</script>

</body>
</html>
반응형
Comments