Search code examples
javascriptkendo-uikendo-template

kendo UI: can I use conditions in a bound template?


I have this template:

<script id="tmpl_bound_menuitem" type="text/x-kendo-template">
    <li data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name"></a>
    </li>
</script>

A View uses that to create menu items from a menuModel:

<ul class="dropdown-menu" data-bind="source: menu_test" data-template="tmpl_bound_menuitem"></ul>

This works fine. But if I set this data:

menuModel.set("menu_test", [
    { name: "MenuItem1", href:"#/route1" },
    { name: "",         style: "divider" }
]);

The result has undefined values, as expected:

<ul class="dropdown-menu" data-bind="source: menu_test" data-template="tmpl_bound_menuitem">
    <li class="undefined" data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name" href="#/route1">MenuItem1</a>
    </li>
    <li class="divider" data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name" href="undefined"></a>
    </li>
</ul>

Now, the question is: is it possible to make this template work for different types of menu items?

Something like the javascript code in "normal" templates:

# if(href) { #<a data-bind="attr: { href: href }, text: name"></a># } #

But this doesn't work here because href is undefined.


Solution

  • Yes, you can use conditions.

    If you write if (href)... you need to have href defined otherwise JavaScript will not find it. So, instead, what you should write is:

    # if(data.href) { #<a data-bind="attr: { href: href }, text: name"></a># } #
    

    Where data is the variable that KendoUI automatically generates containing your object model.

    Kendo UI allows to shortcut to href because in the JavaScript code they have something like:

    with (data) {
       // Code for expanding your template
       ...
    }
    

    But this requires having href otherwise the template expansion cannot determine if href is a global variable or a member of data.