【问题标题】:how to use template with knockout, knockout mapping and jsrender如何将模板与敲除、敲除映射和 jsrender 一起使用
【发布时间】:2012-10-03 20:35:58
【问题描述】:

我想使用 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>

输出的样子:

【问题讨论】:

标签: knockout.js knockout-mapping-plugin jsrender


【解决方案1】:

您必须安装自己的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 的原生模板会更好。

【讨论】:

  • 在这种情况下你会如何使用 Knockout 的原生模板?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2012-09-04
    • 2013-09-22
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多