This is a migrated thread and some comments may be shown as answers.

Dynamically selecting data templates

2 Answers 332 Views
Templates
This is a migrated thread and some comments may be shown as answers.
Brian Vallelunga
Top achievements
Rank 1
Brian Vallelunga asked on 24 Apr 2012, 10:05 PM
I'm attempting to use the MVVM framework to bind an array of objects to some templates. In my scenario, assume I have an array of animals. I want to use a different template for each animal. How can this be accomplished?

The code might look like this:

var vm = kendo.viewModel({
   animals: []
});
  
vm.animals.push(new Cat());
vm.animals.push(new Dog());
  
kendo.bind("#farm", vm);

With HTML that looks like:

<div id="farm">
<div data-template="animal-template" data-bind="source: animals"></div>
</div>
  
Here is where I would define the different templates for each animal



2 Answers, 1 is accepted

Sort by
0
Accepted
Petyo
Telerik team
answered on 25 Apr 2012, 08:46 AM
Hi,

Different templates for different types of objects are not supported at the moment, but you can do something like that:

<script type="text/x-kendo-template">
# if (data instanceof Cat) { #
   This is a cat template!
# } else if (data instanceof Dog) { #
   Woof-Woof!
# } #
</script>


Greetings,
Petyo
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Brian Vallelunga
Top achievements
Rank 1
answered on 25 Apr 2012, 01:24 PM
Thank you Petyo, that will work, although that can get pretty messy rather quickly. Taking that idea and expanding on it, I made that template do nothing besides render other templates. Here's what I ended up with:

<script id="animal-template" type="text/x-kendo-template">
# if (data instanceof Cat) { #
   <div data-template="cat-template" data-bind="source: this"></div>
# } else if (data instanceof Dog) { #
   <div data-template="dog-template" data-bind="source: this"></div>
# } #
</script>

The benefit here is that the individual templates can live elsewhere.
Tags
Templates
Asked by
Brian Vallelunga
Top achievements
Rank 1
Answers by
Petyo
Telerik team
Brian Vallelunga
Top achievements
Rank 1
Share this question
or