如何为提线木偶分配功能.模板

how to assign function to marionette.template

本文关键字:功能 模板 分配 提线木偶      更新时间:2023-09-26

据我所知,marionette.template接受jquery selectorcompiled template string

如果我以如下方式编写代码,则工作良好

 exports.ProductInfoView=Backbone.Marionette.ItemView.extend({
        domInfo:{
            mainTemplateId:"tagProductListTpl",
            tableTemplateId:"taginfoViewTpl"
        },
        template:commomFunctions.templateCompilation("tagProductListTpl",""),
        onRender:function(){
            this.templatingProductInformation();
        },
        modelEvents:{
            "change:currentJson":"templatingProductInformation"
        },
        templatingProductInformation:function(){
            console.log(this.el);
            //this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,"");
        }
    });

注意:commonFunctions.templateCompilation()接受templateId作为第一个参数,接受data作为第二个参数。它将编译handlebars template,并返回已编译的模板。

如果我将该返回值分配给template,则工作正常。

我想制作用于模板的数据,所以我将function传递给template like in the following way.

exports.ProductInfoView=Backbone.Marionette.ItemView.extend({
        domInfo:{
            mainTemplateId:"tagProductListTpl",
            tableTemplateId:"taginfoViewTpl"
        },
        template:function(){
            return commomFunctions.templateCompilation("tagProductListTpl","");
        },
        onRender:function(){
            this.templatingProductInformation();
        },
        modelEvents:{
            "change:currentJson":"templatingProductInformation"
        },
        templatingProductInformation:function(){
            console.log(this.el);
            //this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,"");
        }
    });

这种方式也很好,如果你观察我硬编码的templateId("tagProductListTpl")内部函数。但我不想那样。我想使用类似this.domInfo.mainTemplateId的代码,而不是硬编码。那样就不好用了。

这是投掷错误。我知道它超出了范围。但我怎么能做到这一点。

有人能帮我吗?

谢谢。

我建议您重写负责模板编译的Marionette.TemplateCache.prototype.compileTemplate。看看这篇文章,几乎有同样的问题。

Marionette.TemplateCache.prototype.compileTemplate = function (yourRawTemplate) {
        // In case if template is function
        if (_.isFunction(yourRawTemplate)) {
            return yourRawTemplate;
        } else {
            return Handlebars.compile(yourRawTemplate);
        }
 };

如果从远程服务器加载模板文件,还需要重写Backbone.Marionette.TemplateCache.prototype.loadTemplate。这里的例子:

Marionette.TemplateCache.prototype.loadTemplate = function ( templateId ) {
    var template = '',
        templateUrl = 'path_to_your_template/' + templateId + '.html';
    // Loading template synchronously.
    Backbone.$.ajax( {
        async   : false,
        url     : templateUrl,
        success : function ( templateHtml ) {
            template = templateHtml;
        }
    } );
    return template;
};