view src/implab/text/template-compile.js @ 0:fc2517695ee1

Initial commit, draft import of existing work
author cin
date Thu, 01 Jun 2017 13:20:03 +0300
parents
children f0035923ff3e
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/template-compile'
                    } ]);
                });
            }
        };

        return compile;
    });