jQuery Template サンプル

書籍タイトル

書籍タイトル

元記事:jQuery Templateについてちょっと調べてみた

HTNL

<div>
<h4>書籍タイトル</h4>
<dl id="bookList">
<!- ここにリストが入る -->
</dl>
</div>
<div><input id="load" type="button" value="従来jQueryの方法" /></div>

HTNL (jQuery Template)

<div>
<h4>書籍タイトル</h4>
<dl id="bookList2">
<script id="bookList2Tmpl" type="text/x-jquery-tmpl">
<dt>${title}</dt>
<dd>${description}</dd>
</script>
</dl>
</div>
<div><input id="loadTmpl" type="button" value="jQuery Templateを使う方法" /></div>

JacaScript

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script type="text/javascript">
/*
*	Ajax処理の結果
*/
var result = [
	{ "title":'逆襲ノマド', 	"description": '新しい仕事' 	},
	{ "title":'黄昏サスペンデッド', "description": '今日は早く帰ろう'	},
	{ "title":'やる気 not Fount!', 	"description": 'ノーコメント'		}
];

(function($){

	//従来の方法
	$( "#load" ).click(function(e){
	
		//クリア
		//$("#bookList").children().remove();
	
		//result = Ajax処理の結果とか
		var jsonAray = result;
		var bookList = "";
		for (var i = 0; i < jsonAray.length; i ++) {
			var book = jsonAray[i];
			bookList += "<dt>" + book.title + "</dt>";
			bookList += "<dd>" + book.description + "</dd>";
		}
		$("#bookList").append( bookList );
	});
	

	//テンプレート使う
	$( "#loadTmpl" ).click(function(e){
	
// テンプレートの記述場所によっては注意が必要
// (scriptタグごと消える)
//$("#bookList2").children().remove();
		
	    //result = Ajax処理の結果とか
		var jsonAray = result;
		var bookList = $( "#bookList2Tmpl").tmpl( jsonAray );
	
		$("#bookList2").append( bookList );
	});
	
})(jQuery);
</script>