Last active
December 19, 2015 13:39
-
-
Save pistatium/5963229 to your computer and use it in GitHub Desktop.
= Table Builder = JSON等から手っ取り早くTableタグを生成する用の関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
データを手っ取り早くテーブルにして表示するための関数 | |
何を表示するかを定義したheaderと、 | |
配列形式で複数行のデータが入ったdataを渡すと | |
テーブルのHTMLを返す | |
*/ | |
var tableBuilder = function(header, data) { | |
var html = '<table class="table"><thead><tr>'; | |
for (var key in header) { | |
html += '<th id="label_' + key + '">' + header[key] + '</th>'; | |
} | |
html += '</tr></thead><tbody>'; | |
for (var i in data) { | |
var d = data[i]; | |
html += '<tr>'; | |
for (var key in header) { | |
if(d[key]) { | |
html += '<td>' + d[key] + '</td>'; | |
} else { | |
// 対応するキーがない場合 | |
html += '<td>--</td>'; | |
} | |
} | |
html += '</tr></tbody>'; | |
} | |
html += '</table>'; | |
return html; | |
} | |
/* テーブルのヘッダーを定義 */ | |
var header = { | |
'id' : '#', | |
'title' : 'タイトル', | |
'updated_at' : '更新日', | |
}; | |
/* テーブルにしたいデータ */ | |
var data = [ | |
{'id':1, 'created_at':'2013/05/01', 'updated_at':'2013/07/01','title':'記事1'}, | |
{'id':2, 'created_at':'2013/06/01', 'updated_at':'2013/07/02','title':'記事2'}, | |
{'id':3, 'created_at':'2013/07/01','title':'記事3'}, | |
]; | |
tableBuilder(header, data); | |
/* | |
################# | |
出力結果 | |
################# | |
<table class="table"> | |
<thead> | |
<tr> | |
<th id="label_id">#</th> | |
<th id="label_title">タイトル</th> | |
<th id="label_updated_at">更新日</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td>1</td> | |
<td>記事1</td> | |
<td>2013/07/01</td> | |
</tr> | |
</tbody> | |
<tbody> | |
<tr> | |
<td>2</td> | |
<td>記事2</td> | |
<td>2013/07/02</td> | |
</tr> | |
</tbody> | |
<tbody> | |
<tr> | |
<td>3</td> | |
<td>記事3</td> | |
<td>--</td> | |
</tr> | |
</tbody> | |
</table> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment