jQuery.tmpl
今更復習。
by FiNGAHOLiC
HTML
<script src="https://raw.github.com/jquery/jquery-tmpl/master/jquery.tmpl.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script id="tmplUser" type="text/x-jquery-tmpl">
<li>${name} (${age})</li>
</script>
<ul id="users"></ul>
<script id="tmplChara" type="text/x-jquery-tmpl">
<li>
${name}
<ul>
<!-- tmpl()で入れ子の配列をさらにループ処理 -->
<!-- http://api.jquery.com/template-tag-tmpl/ -->
{{tmpl(items) '#tmplCharaItem'}}
</ul>
</li>
</script>
<script id="tmplCharaItem" type="text/x-jquery-tmpl">
<li class="item">${name} (${power})</li>
</script>
<ul id="charas"></ul>
CSS
ul{
padding-left:25px;
list-style:disc;
}
li{
margin-left:20px;
}
#users{
margin-bottom:30px;
}
JavaScript
(function($, window, document, undefined){
// http://cryks.hateblo.jp/entries/2011/03/30
$(function(){
// 普通(・∀・)
(function(){
var users = [
{ name: 'hogeo', age: 31 },
{ name: 'hogemi', age: 30 },
{ name: 'hogetarou', age: 68 },
{ name: 'hogeko', age: 65 }
];
$('#tmplUser').tmpl(users).appendTo('#users');
}());
// 複雑( ´Д`)
(function(){
var chara = [
{
name: 'hogeo',
items: [
{ name: 'knife', power: 10 },
{ name: 'sword', power: 200 }
]
},
{
name: 'hogemi',
items: [
{ name: 'knife', power: 100 },
{ name: 'sword', power: 20 }
]
}
];
$('#tmplChara')
.tmpl(chara)
.appendTo('#charas')
.delegate('.item', 'click', function(){
// テンプレートからレンダリングした要素はtmplItem()でデータを取得できる(・∀・)
var item = $(this).tmplItem();
console.log(item.data.power);
});
}());
});
}(jQuery, window, this.document));