Store a jsRender template in a separate js file

后端 未结 5 623
天涯浪人
天涯浪人 2020-12-14 19:24

Is it possible to store a jsRender template in a separate file?

I want to store it in a separate file and make a reference of it in my page.

something like t

5条回答
  •  轮回少年
    2020-12-14 19:37

    Here is a function I wrote to load one or more external templates at once. It also caches the templates so if one is already loaded it won't load again.

    function loadTemplates() {
        var toLoad = [],
            loadAll = $.Deferred();
    
        $.each(arguments, function(i, templateName) {
            var filepath = '/path/to/templates/' + templateName + '.html',
                loadTemplate = $.Deferred();
    
            toLoad.push(loadTemplate);
    
            if ($.templates[templateName]) {
                loadTemplate.resolve();
            } else {
                $.get(filepath , function(html) {
                    var newTemplate = {};
                    newTemplate[templateName] = html;
                    $.templates(newTemplate);
                }).fail(function() {
                    throw 'Could not load template at '+filepath;
                }).done(function() {
                    loadTemplate.resolve();
                });
            }
        })
    
        $.when.apply($, toLoad).done(function() {
            loadAll.resolve();
        });
    
        return loadAll;
    }
    

    Use it like so:

    loadTemplates('modal','itemDetail', 'itemsList').done(function() {
        // do stuff when all templates are loaded
        $('#viewItemDetail').on('click',function() {
            $.render.itemDetail({
                id:'123',
                name:'Cool Thing',
                description:'This thing is really cool.'
            });
        });
    });
    

提交回复
热议问题