3

I'm not understanding something basic about Kendo templates, so maybe someone can explain this to me. This example of a template for a cell in a grid comes from Telerik sample code.

template:"<input type='checkbox' #= IsAdmin ? checked='checked':'' # />

Ultimately, this produces an input tag which, if the value of IsAdmin is true, will include "checked='checked'"

I don't understand the evaluation context of

#= IsAdmin ? checked = 'checked' : '' #

Documentation says that "#=" indicates "render as literal" (whatever that means), and I understand that "IsAdmin" is a value provided when the template is evaluated/executed.

What follows the #= looks like Javascript, but if it were only that, it would merely set the value of a variable named "checked" to either 'checked' or an empty string.

Is the ? operator here really javascript, or is it Kendo templating language? I've seen no mention of a Kendo-specific language with operators. But if this is truly a Javascript ? operator, how does it work that we get a literal "checked='checked' out of this instead of setting a var named "checked" with value 'checked'.

Call me puzzled.

Lars Höppner
  • 18,252
  • 2
  • 45
  • 73
Elroy Flynn
  • 3,032
  • 1
  • 24
  • 33

1 Answers1

5

It's JavaScript. Using this template string:

"<input type='checkbox' #= isAdmin ? checked='checked' : '' # />"

Template.compile will generate a function like this one:

function anonymous(data) {
    var o, e = kendo.htmlEncode;
    with(data) {
        o = '<input type=\'checkbox\' ' + (isAdmin ? checked = 'checked' : '') + ' />';
    }
    return o;
}

As you can see, your template section is used without changes. When your cell is rendered, this function is executed (your data item, e.g. the grid's row model, is passed in) and the resulting string is used as content for the cell.

From the perspective of the rendered HTML, this here:

"<input type='checkbox' #= isAdmin ? checked='checked' : '' # />"

is equivalent to:

"<input type='checkbox' #= isAdmin ? 'checked' : '' # />"

since checked='checked' will simply evaluate to 'checked'. Using the first variant however will also set the checked attribute on the data which is passed into the template function (see demo for illustration).

Lars Höppner
  • 18,252
  • 2
  • 45
  • 73
  • 2
    Aha! I get it. My confusion is due to the fact that I didn't realize that the generated html, in the case of a true condition, is simply . I didn't know that an attribute without a value is even legal. And when inspected in the browser, the tools are 'helpful' enough to convert it to standard form and show me "checked='checked'" even though that wasn't the original html. So I've been spending time wondering how the template generated "checked='checked'" when it never did. Gracias. – Elroy Flynn Dec 23 '13 at 15:42