2

我想使用 jsRender 模板来fullName渲染firstName + ' ' + lastName. 它不是用数据呈现模板,而是呈现为{{=firstName}} {{=lastName}}. 我怎样才能使这项工作?

现场示例:http: //jsbin.com/inijay/2/edit

JS:

var data = { "firstName": "Ian", "lastName": "Davis" };
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

HTML:

<input data-bind="value: firstName" type="text" />
<input data-bind="value: lastName" type="text" />
<span data-bind="template: 'fullNameTemplate'"></span>

模板:

<script id="fullNameTemplate" type="text/x-jquery-tmpl">
  {{=firstName}} {{=lastName}}
</script>

输出的样子:损坏的 jsrender 模板输出

4

2 回答 2

2

您必须安装自己的templateEngine. 这是完成的结果:http: //jsbin.com/inijay/3/edit

以下是相关代码:

ko.jsrenderTemplateEngine = function () { };
ko.jsrenderTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), {
    renderTemplateSource: function (templateSource, bindingContext, options) {
        // Precompile the wrapping div for templating
        var precompiled = templateSource['data']('precompiled');
        if (!precompiled) {
            precompiled = $('<div>', { text: templateSource.text() });
            templateSource['data']('precompiled', precompiled);
        }
        // Unwrap observables
        var unwrapped = ko.mapping.toJS(bindingContext.$data);
        // Render and parseHTMLFragment
        return ko.utils.parseHtmlFragment(precompiled.render(unwrapped));
    }
});
ko.setTemplateEngine(new ko.jsrenderTemplateEngine());

我还更改了您的 jsrender 模板:

<script id="fullNameTemplate" type="text/x-jquery-tmpl">
    {{:firstName}} {{:lastName}}
</script>

我从这里抄袭了基本的代码设计:http: //knockoutjs.com/documentation/template-binding.html#note_6_using_the_underscorejs_template_engine

附带说明一下,这个解决方案似乎并不是那么快,因为 jsrender 的最优性由于不得不一直打开 observables而变得无用。我相信使用 Knockout 的原生模板会更好。

于 2012-10-03T21:59:52.790 回答
0

使用 jQuery.tmpl 的解决方案: http: //jsbin.com/inijay/5/edit文档说此时它会更新到 jsRender,但显然不是。此处的文档:knockoutjs.com/documentation/template-binding.html

于 2012-10-04T00:43:34.027 回答