Dynamically selecting data templates

3 posts, 1 answers
  1. Brian Vallelunga
    Brian Vallelunga avatar
    88 posts
    Member since:
    May 2008

    Posted 24 Apr 2012 Link to this post

    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. Answer
    Petyo
    Admin
    Petyo avatar
    2439 posts

    Posted 25 Apr 2012 Link to this post

    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!
  3. Kendo UI is VS 2017 Ready
  4. Brian Vallelunga
    Brian Vallelunga avatar
    88 posts
    Member since:
    May 2008

    Posted 25 Apr 2012 Link to this post

    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.
Back to Top