使JQuery模板可重用

时间:2011-08-09 08:50:50

标签: jquery jquery-templates

我想创建一个将在项目范围内使用的jQuery模板。我更喜欢将模板放在一个单独的文件中,并使用template函数在项目启动时编译它们。

我不希望在脚本标记中的标记中包含模板。这有可能,我该怎么做?

2 个答案:

答案 0 :(得分:0)

正如RoccoC5所建议的那样,您可以定义一个小插件,它将获取您的远程模板,然后将其内容附加到头部的脚本标记中:

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

并将其用于:

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

或:

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

希望得到这个帮助。

答案 1 :(得分:0)

模板仅用作字符串,因此您甚至不必注入脚本。只需将字符串直接传递给jQuery.template。所以调整@abernier建议的内容,你可以做类似以下的事情。我假设您将文件命名为与要使用的模板名称相同的名称,并将它们存储在TMPLPATH中。

    $.loadTmpl = function (name) {
        return $.get(TMPLPATH + name + ".tmpl").success(function (content){
            $.template(name, content);
        });
    };
相关问题