Kendo UI Grid handling missing values in column templates

1.6k views Asked by At

I use Kendo UI Grid for displaying array data with objects having some fields missing. Here is js code:

var arr = [{b: "b1"}, {a: "a2", b: "b2"}];

$("#grid").kendoGrid({
    dataSource: arr,
    columns: [
        { 
            title: "The A column",
            field: 'a'
        }, { 
            title: "The B column",
            template: '<i>#=b#</i>'
        }]
});

In this example the grid works well and displays missing "a" value in first row as empty cell.

When working with column template:

$("#grid").kendoGrid({
    dataSource: arr,
    columns: [
        { 
            title: "The A column",
            template: '<b>#=a#</b>'
        }, { 
            title: "The B column",
            template: '<i>#=b#</i>'
        }]
});

It displays an error in console: Uncaught ReferenceError: a is not defined. Even replacing template with:

template: '<b>#=a || ""#</b>'

expression instead does not help, so I have to manually set the missing values to empty string before constructing the table. Is there way to avoid this?

1

There are 1 answers

0
OnaBai On BEST ANSWER

Instead of:

template: '<b>#=a || ""#</b>'

You should use:

template: '<b>#=data.a || ""#</b>'

Where data is predefined by KendoUI and is equal to the row data. Otherwise JavaScript doesn't know that a should be part of the data and thinks that it is a variable per-se throwing the error.

You can see it running in the following snippet

$(document).ready(function() {
  var arr = [{b: "b1"}, {a: "a2", b: "b2"}];

  $("#grid").kendoGrid({
    dataSource: arr,
    columns: [
      { 
        title: "The A column",
        template: '<b>#= data.a || ""#</b>'
      }, { 
        title: "The B column",
        template: '<i>#=b#</i>'
      }]
  });
});
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.default.min.css">

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>

<div id="grid"></div>