Allen4Tech Allen4Tech - 3 months ago 69
AngularJS Question

how to create separate column template in Kendo-UI grid

I begin to use Kendo-UI in my project, I want one of my column show an image button and a field, similar with 'Contact Name' in documentation here.Then I was checking the documentation, and got the code as below.



columns: [{
template: "<div class='customer-photo'" +
"style='background-image: url(../content/web/Customers/#:data.CustomerID#.jpg);'></div>" +
"<div class='customer-name'>#: ContactName #</div>",
field: "ContactName",
title: "Contact Name",
width: 240
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}]





I don't think write html in the template directly is a good way, especially with a very complex template. Then I found another solution from the documentation.

"template": "kendo.template($('comments-template').html())"


This is more sensible in my scenario. But I'm very confused where to define the template is better. I also use AngularJS. Should I create a new file to write the template or any other place?

Thanks

Answer

The columns.template property expects a string or a function that returns a string. You can either use a <script> tag in the HTML markup...

<script id="script-template-id" type="text/x-kendo-template">
    <div class="myClass">#: FieldName #</div>
</script>

...

<script>
// ...

columns: [{
    title: "My Template Column",
    template: $('#script-template-id').html()
}]

// ...
</script>

... or use a string variable that is defined wherever you prefer, including an external JavaScript file (given that it will be registered early enough for the variable to be available):

var templateStringVariable = '<div class="myClass">#: FieldName #</div>';

// ...

columns: [{
    title: "My Template Column",
    template: templateStringVariable
}]

Note that this syntax will not work, as the JavaScript code itself is stringified:

"template": "kendo.template($('comments-template').html())"
Comments