我想使用 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>
输出如下:
最佳答案
您必须安装自己的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 的最佳性由于必须始终解开可观察对象而变得无用。我相信使用 Knockout 的原生模板会更好。
关于knockout.js - 如何使用带有 knockout 、 knockout 映射和 jsrender 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12716486/