动态加载js中的嵌套模板(没有数据传递)

时间:2012-06-14 07:12:33

标签: javascript jquery html templates

我正在研究离线原型(html,css和js),我需要一个简单的机制,我可以将我的标记分成几个外部模板文件,以便更好地进行维护并使其可重复使用。

主要是这些外部模板不会有任何类型的数据模板,它只包含静态html,

我需要编写一个脚本,它将解析所有data-template-url属性,并将相应的模板文件加载到该DOM元素中,如果加载的模板有data-template-url,脚本也会执行相同(无论我的标记中有多少嵌套模板)

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

我已经完成了以下脚本来完成这项工作,但不处理嵌套模板

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

感谢任何人都可以提供帮助:)

1 个答案:

答案 0 :(得分:1)

如果你想保持你的方法:

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