Making JQuery templates reusable

元气小坏坏 提交于 2019-12-06 09:28:49

问题


I want to create a jQuery template(s) that will be used project wide. I would prefer to put the templates in a separate file or files and compile them on project start up using the template function.

I don't want to have the templates in the markup, in script tags. Is this possible and how would I do it?


回答1:


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.




回答2:


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);
        });
    };


来源:https://stackoverflow.com/questions/6993590/making-jquery-templates-reusable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!