Reputation: 1182
I have a case where Kendo grid columns are dynamic and
I have two rest api's one that gives me Metadata about column
metadata = [{title1, field1}, {title2, field2}...]
I will need to apply generic templates for some columns
I am iterating through metadata and building the columns array
forEach(col in metadata){
if(title === 'Name'){
columns.push({
title: col.title,
template: nameTemplate
});
}
if(title === 'Date'){
columns.push({
title: col.title,
template: dateTemplate
});
}
if(title === 'Salary'){
columns.push({
title: col.title,
template: currencyTemplate
});
}
else{
columns.push({
title: col.title,
field: col.field
});
}
}
function dateTemplate(dataItem) {
if(date){
return kendo.toString(kendo.parseDate(dataItem.date, 'yyyy-MM-dd'), 'MM/dd/yyyy');
}
return '';
}
In datetemplate I get the dataItem and bind the date field.
Is there a way where I can use the template for multiple columns such as, for example if there are multiple date columns in my grid such as Start Date, End Date, Date of Joining, Date of Birth
and if I choose to apply a single template for all the columns by passing fieldName to the template function as below
I tried this way but this doesn't work.
1. format : "{0:MM/dd/yyyy}" //this doesn't work and may be because date is returned as a string in json.
2. if(col.title.indexOf('Date')>0){ //check if title is of date type
columns.push({
title: col.title,
template: dateTemplate(fieldName) //pass fieldname
});
}
I also tried
3. if(col.title.indexOf('Date')>0){ //check if title is of date type
columns.push({
title: col.title,
template: function(dataItem) { dateTemplate(dataItem, fieldName) } //pass fieldname
});
}
function dateTemplate(dataItem, field){
return kendo.toString(kendo.parseDate(dataItem[field], 'yyyy-MM-dd'), 'MM/dd/yyyy');
}
This always ties the same date to all columns and all rows.
Please help me with this genericTemplating in kendogrid
Upvotes: 0
Views: 684
Reputation: 24738
You could use a template string instead of a function:
"#= kendo.toString(kendo.parseDate(" + field + ", 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
Here is some example code and a demo:
var metadata = [
{
field: "StartDate",
title: "Start Date",
},
{
field: "EndDate",
title: "Emd Date",
}
];
var columns = [];
for (var i = 0; i < metadata.length; i++){
var col = metadata[i];
if(col.title.indexOf('Date')>0){
columns.push(
{
field: col.field,
title: col.title,
template: dateTemplate(col.field)
});
}
}
function dateTemplate(field){
return "#= kendo.toString(kendo.parseDate(" + field + ", 'yyyy-MM-dd'), 'MM/dd/yyyy') #";
}
Upvotes: 1