Making JQuery templates reusable

别等时光非礼了梦想. 提交于 2019-12-04 17:56:36

As RoccoC5 suggested it, you can define a small plugin which will fetch your remote template and then append its content into a script tag to the head:

(function ($) {
    $.loadTmpl = function (url, name) {
        return $.get(url).success(function (content){
            $("head").append($('<script/>', {
                id: name,
                type: 'text/template'
            }).html(content));
        });
    };
}(jQuery));

and use it with:

$.loadTmpl('hi.html', 'hi').done(function () {
    $('#hi').tmpl({name: 'Tom'}).appendTo('body');
});

or:

$.when(
    $.loadTmpl('foo.html', 'foo'),
    $.loadTmpl('bar.html', 'bar'),
    ...
).done(function () {
    // All your templates are now loaded
});

Hope this help.

Templates are just used as strings, so you don't even have to inject scripts. Just pass the string straight to jQuery.template. So tweaking what @abernier suggested, you can do something like following. I make the assumption that you name the files the same name as the template name you want to use and you store them in TMPLPATH.

    $.loadTmpl = function (name) {
        return $.get(TMPLPATH + name + ".tmpl").success(function (content){
            $.template(name, content);
        });
    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!