JSFiddle - React, Tailwind, and code Playground
by mach3ss
HTML
<h2>サンプル (Array)</h2>
<table id="test01">
<caption>IEの誕生日メモ</caption>
<thead>
<tr>
<th>バージョン</th>
<th>誕生日</th>
<th>サポート終了日</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/html" id="template-test01">
<tr>
<td>{{version}}</td>
<td>{{birthDay}}</td>
<td>{{unsupported}}</td>
</tr>
</script>
<h2>サンプル (Object)</h2>
<dl id="test02"></dl>
<script type="text/html" id="template-test02">
<dl>
<dt>名前</dt>
<dd>{{name}}</dd>
<dt>スクリーンネーム</dt>
<dd>{{screenName}}</dd>
<dt>備考</dt>
<dd>{{note}}</dd>
</dl>
</script>
CSS
#test01{
border-collapse:collapse;
border:1px solid #ccc;
margin:2em 10px;
}
#test01 caption{
text-align:center;
}
#test01 th, #test01 td{
border:1px solid #ccc;
text-align:center;
padding:3px;
}
#test01 th{
background-color:#eee;
font-weight:bold;
}
#test02{
margin:1em 10px;
}
#test02 dt{
font-weight:bold;
}
#test02 dd{
margin-left:1em;
}
JavaScript
/**
* jquery.render.js
* @version 1.0
* @author mach3
* @requires jQuery http://jquery.com/
*/
$.fn.extend({
/**
* Function to render HTML from template and data
* @param {object} data Collection of data ( array or object )
* @return {object} jQuery object which contains rendered HTML.
* @example $("script#template-example").render( data ).appendTo( $("#Container") );
*/
render:function( data ){
var tmpl = this.html(), result = "",
create = function(t,d){
var m = t.match(/{{(.+?)}}/g) || [], r = t;
$.each( m, function(i,k){
var v = d[ k.replace(/{|}/g, "") ];
r = r.replace( k, ( v === undefined ) ? "" : v );
});
return r;
};
if( data === undefined ){ return $( tmpl.replace(/{{(.+?)}}/g, "") ); }
if( !(data instanceof Array) ){ return $( create(tmpl, data) ); }
$.each( data, function(i,o){ result += create(tmpl,o); } );
return $(result);
}
});
var data01 = [
{ version:"8", birthDay:"2009/3/20", unsupported:"-" },
{ version:"7", birthDay:"2006/11/2", unsupported:"-" },
{ version:"6", birthDay:"2001/8/27", unsupported:"2014/4/8" },
{ version:"5.5", birthDay:"2000/7/13", unsupported:"2005/12/31" },
{ version:"5", birthDay:"1999/3/18", unsupported:"2010/7/13" }
];
$("#template-test01").render( data01 ).appendTo($("#test01 tbody"));
var data02 = { name:"まっは", screenName:"mach3ss", note:"ねるのだいすき" };
$("#template-test02").render( data02 ).appendTo($("#test02"));