概要
jQueryのDataTablesのrender
オプションを使用して、複数のフィールドを連携して表示するよう実装しました。使い方について説明します。
サンプルコード
以下のようにrender
関数を使用して、condition1
、condition2
、condition3
の値を連結して表示することができます。
data
にはバックエンド側からデータが連携される前提です(私はdjangoを利用しました)。
$(document).ready(function () {
var RenderTable = function (data) {
var table = $('#sample_table').DataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/3cfcc339e89/i18n/Japanese.json"
},
// 略
data: data,
columns: [
{
"data": null,
"title": '連結名',
"render": function (data, type, row) {
return row.condition1 + ' ' +
row.condition2 + ' ' +
row.condition3;
}
},
// 略
ポイントは、"data": null:
を設定することによって、render
関数内でrow
オブジェクト全体にアクセスできるようになり、また値を自由にカスタマイズできること。null
になっているので、特定のキーに依存せず、この関数内で自由にデータを組み合わせて表示することができるようになるのです。
公式ドキュメントにも以下のように記載されています。
Functions
Using columns.render is the most common method as it provides absolute control over the data that will be displayed to the end user (this is a regular Javascript function, so you can do virtually anything you wish with the data).The function is passed in three parameters:
- The data that is pointed to by columns.data. If columns.data is null, null will be the value given here.
- The data type being requested by DataTables - this allows the function to support orthogonal data.
- The original and full data object or array for the row.
「If columns.data is null, null will be the value given here.
」と記載されているように、null
としておけばrender
の結果が入るようになっています。
上記のようにすることで、複数のフィールドの値を組み合わせて1つのセルに表示することができました。
より柔軟に表記を変えることができて良いですね。