Search code examples
templateskendo-uikendo-treeview

Kendo UI Treeview Sprite-Altering Template


I have a kendo Treeview bound to a remote hierarchical datasource(JSON file).

I want to add sprites next to each one of the nodes according to what the node is.If the node doesn't have children then I want it to have the "file" sprite,if the node has children I want it to have the "folder" sprite.(The sprites are provided from kendo,the ones that are on the demos)

I'm a bit confused with the way templates work,can I alter the sprite for each of the nodes dynamically with the template?Any good example and a bit of explanation to get me going would help a lot.

Thx


Solution

  • In the following code what I do is define a template that checks if the node being rendered has items (subnodes) or not. If it has, it displays an icon from default sprite file (k-i-plus) otherwise it shows a different icon (k-i-refresh).

    function loadMore() {
        var uuid = $(this).data("uid");
        var node = tree.findByUid(uuid);
        tree.insertBefore(content, node);
        tree.remove(node);
        tree.expand(".k-item");
        addLoadMore(".k-i-refresh");
    }
    
    function addLoadMore(clss) {
        $(clss, tree.element).closest(".k-item").on("click", loadMore);
    }
    
    var content = [
        {
            text :"node1",
            items:[
                { text:"node1.1" },
                { text:"node1.2" },
                { text   :"node1.3",
                    items:[
                        { text:"node1.3.1" },
                        { text:"node1.3.2" },
                        { text:"node1.3.3" },
                        { text:"node1.3.4" }
                    ] },
                { text:"node1.4" }
            ]
        }
    ];
    
    var tree = $("#tree").kendoTreeView({
        dataSource:content,
        template  :"<span class='k-icon #= item.items ? 'k-i-plus' : 'k-i-refresh' #'></span>#= item.text #"
    }).data("kendoTreeView");
    tree.expand(".k-item");
    addLoadMore(".k-i-refresh");
    

    What you would need to do if replace k-i-plus by the CSS class name that defines the folder and change k-i-refresh by the CSS class name for the file.

    If you need information on writing template there is a pretty good documentation in here.