Not understanding this kendo template that generates a checkbox in a grid

旧巷老猫 提交于 2020-01-21 12:15:17

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/20737106/not-understanding-this-kendo-template-that-generates-a-checkbox-in-a-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!