Re-create jQuery templates

I want to create a jQuery template that will be used throughout the project. I would prefer to put the templates in a separate file or files and compile them when the project starts, using the template function .

I do not want to have templates in the markup, in script tags. Is this possible and how will I do it?

+2
source share
2 answers

As suggested by RoccoC5, you can define a small plugin that will select your remote template and then add its contents to the script tag in 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
});

I hope for this help.

0
source

, . jQuery.template. , , @abernier, - . , , , , TMPLPATH.

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

Source: https://habr.com/ru/post/1771745/


All Articles