loading nested templates in js dynamically (no data passed)

I am working on an offline prototype (html, css and js), and I need a simple mechanism in which i can separate my markup into several external template files for better maintenance and to make it reusable..

mainly these external templates will not have any type of data templating, it will contain only static html,

I need to write a script, which will parse all data-template-url attributes, and load the corresponding template file into that DOM element, and if the loaded template has a data-template-url, the script will also do the same (no matter how much nested templates there are in my markup)

<div class="some-component" data-template-url="components/user-details.html">
    <!-- template content will be loaded here -->
</div>

I have done the following script which will do the job, but does not handle nested templates

(function($){

    $(function(){

        var attr = 'data-template-url';

        $('[' + attr + ']').each(function(){
            var $self = $(this)
            ,   url = $self.attr(attr);

            $.get(url, function(data){
                $(data).appendTo($self);
            });
        });

    });
})(jQuery);

appreciate if anyone can help :)

Answers


If you want to keep your approach:

(function($){

    $(function(){

        var loadTemplates = function () {

            var 
                /* template url attribute */
                attr = 'data-template-url',
                /* load status attribute */
                state = 'data-template-state',
                /* load done value for status attribute */
                done = 'ready';

            /* for all elements with template url not in ready state */
            $('[' + attr + ']:not([' + state + '="' + done + '"])')
            .each(function () {

                /* fetch url */
                var url = $(this).attr(attr);

                /* load content and append */
                $(this).load(url, function () {

                    /* set state to ready */
                    $(this).attr(state, done);

                    /* do another run for nested templates */
                    loadTemplates();

                });

            });
        };

        /* start */
        loadTemplates();
    });

})(jQuery);

Need Your Help

Using shared library in Gyp in node-sqlite3

node.js sqlite gyp

I'm new to Gyp. Instead of compiling my dependency, I would like to use a shared library, in particular, the libsqlite3.so which is already on my machine. The main binding.gyp currently looks like

Drupal theme - change slideshow images

image drupal drupal-7 slideshow

Using Drupal 7, "business" theme, I want to change the default slideshow images of the theme to my own images.