view src/Kachkaev/JstmplBundle/Resources/assets/js/tmpl.js @ 0:493bcb69166c

added public content
author Daniel Wolff
date Tue, 09 Feb 2016 20:54:02 +0100
parents
children
line wrap: on
line source
tmpl = (function() {

    var tmpl = {};

    tmpl.autoload = [];

    /**
     * Renders template from a preloaded collection or current page
     * @param template template id, e.g. "calendar:flash_error-load"
     * @returns jQuery object
     */
    tmpl.render = function(template, data, options) {
        //Loading a preloaded template
        $result = $.tmpl(template, data, options);
        // Use of a preloaded template failed. Getting template from current page (<script id="...">)
        if ($result.text().indexOf(template) == 0) {
            $result = $.tmpl($("#"+template.replace(':','\\:')).html(), data, options);
        };
        // Both cases failed. Will return an empty object.
        if (!$result.text || $result.text().indexOf(template) == 0) {
            console.warn('Could not find template '+template);
            $result = $();
        }

        return $result;
    };

    tmpl.loadCollection = function(collectionName) {
        $.ajax({
            url : '/tmpl/' + collectionName + '.html',
            success : function(result) {
                $(result).each(function(i, t) {
                        var $t = $(t);
                        var id = $t.attr('id');
                        if (id) {
                            $.template(id, $t.html());
                        }
                    });
                },
            async : false
        });
    };

    $(function() {
        $.each(tmpl.autoload, function(i, collectionName){
            tmpl.loadCollection(collectionName);
        });
    });

    return tmpl;
})();