Dynamically load jQuery templates

For jQuery template:

http://api.jquery.com/category/plugins/templates/

I want to be able to dynamically download templates from the server, and not predefine it on the page.

The demos I've seen in projects use predefined templates. After some research, it turned out that this is possible.

I am trying to do this and it does not work:

<script src="child.html" type="text/x-jquery-tmpl"></script>

I tried to do this and it does not work:

$(function () {
    $.get("child.html", function (data) {
        //Add template
        $.template("tmplChild", data);
    });

    //template binds before async call is done
    $.tmpl("tmplChild").appendTo("body");
});

And finally, I got to the next hack:

so.html (This is the main page):

<html>
<head>
<title></title>
</head>
<body>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

<script type="text/javascript" src="so.js"></script>

<script type="text/javascript">

    $(function () {
        initTemplates(templateReady);
    });

    function templateReady() {
        $.tmpl("tmplChild").appendTo("body");
    }

</script>
</body>
</html>

child.html (this is a child template)

<h1>Child Loaded</h1>

so.js (This is my hack for ajax loading js templates)

function initTemplates(callback) {
    var templateUrl = "child.html";
    var templateName = "tmplChild";

    initTemplate(templateUrl, templateName, callback);
}

function initTemplate(url, name, callback) {
    var opts =
        {
            type: "GET",
            url: url,
            dataType: ($.browser.msie) ? "text" : "xml",
            success: function (data) {
                xmlCallback(data, name, callback);
            },
            error: function (x) {
                xmlCallback(x.responseText, name, callback);
            }
        }

    $.ajax(opts);
}

function xmlCallback(data, name, callback) {

    if (typeof data != "string") {
        if (window.ActiveXObject) {
            var str = data.xml;
            data = str;
        }
        // code for Mozilla, Firefox, Opera, etc.
        else {
            var str = (new XMLSerializer()).serializeToString(data);
            data = str;
        }
    }

    //only takes strings!
    $.template(name, data);

    callback();
}

And that’s what I don’t like about it.

  • This does not work in Chrome
  • It seems like a lot of code is just loading some kind of template
  • $(document).ready(). templateReady() " ".

?

,

Chi

+5
2

, ajax, , ( .Net). , ajax .

+2

, <script>. $.tmpl(body, params) DOM.

, "not really script" <script>, .

edit — :

$.get("/some/url/for/a/template", function(templateBody) {
  var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});
+3

All Articles