view src/implab/text/template-compile.js @ 11:67a5de7581ad

fixed typo in djol/WFSSource
author cin
date Mon, 21 Aug 2017 18:06:30 +0300
parents f0035923ff3e
children 23be39fd3851
line wrap: on
line source

define(
    [ "dojo/request", "./format" ],
    function(request, format) {
        var compile = function(str) {
            var code = "var p=[],print=function(){p.push(foramt.apply(null,arguments));};" +
                // Introduce the data as local variables using with(){}
                "with(obj){p.push('" +
                // Convert the template into pure JavaScript
                str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(
                    /(^|%>)[^\t]*/g,
                    function(x) {
                        return x.replace(/('|\\)/g, "\\$1");
                    }).replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');")
                    .split("%>").join("p.push('") + "');}return p.join('');";
            /* jshint -W054 */
            try {
                var compiled = new Function("obj, format, nls", code);

                /**
                 * Функция форматирования по шаблону
                 * 
                 * @type{Function}
                 * @param{Object} obj объект с параметрами для подстановки
                 */
                return function(obj) {
                    return compiled(obj || {}, format);
                };
            } catch (e) {
                if (console && console.error) {
                    console.error(code);
                }
            }
        };

        var cache = {};

        compile.load = function(id, require, callback) {
            var url = require.toUrl(id);
            if (url in cache) {
                callback(cache[url]);
            } else {
                request(url).then(compile).then(function(tc) {
                    callback(cache[url] = tc);
                }, function(err) {
                    require.signal("error", [ {
                        error : err,
                        src : 'implab/text/template-compile'
                    } ]);
                });
            }
        };

        return compile;
    });