Search code examples
templatesbackbone.jsunderscore.js

decompile _underscore template


i've got many "compiled" underscore template ( some months ago i save compiled templates to on file, and accidentally remove original templates folder... :( ) is it pissible to "decompile" this templates? one of example:

UV.templates["template-button-widget"] = function() {
        return $.trim(function(obj) {
            var __t, __p = "",
                __j = Array.prototype.join,
                print = function() {
                    __p += __j.call(arguments, "")
                };
            with(obj || {}) __p += '\n\n    <div class="button" data-id="' + (null == (__t = data._id) ? "" : _.escape(__t)) + '">\n\n        <div class="icon"></div>\n\n    </div>\n\n';
            return __p
        }.apply(this, arguments))
}, 

Solution

  • If you read over the source of _.template, you'll find it's simple enough that you could reverse it with a few hours of work. Make sure to find the code for your version of underscore (clearly yours isn't the most recent as there are changes), old docs can be found in the changelog.

    Here's the code required to reverse your example template:

    var compiled = function() {
            return $.trim(function(obj) {
                var __t, __p = "",
                    __j = Array.prototype.join,
                    print = function() {
                        __p += __j.call(arguments, "")
                    };
                with(obj || {}) __p += '\n\n    <div class="button" data-id="' + (null == (__t = data._id) ? "" : _.escape(__t)) + '">\n\n        <div class="icon"></div>\n\n    </div>\n\n';
                return __p
            }.apply(this, arguments))
    };
    
    var source = compiled.toString();
    
    // Strip start/end code
    source = source.substring(source.indexOf("with(obj || {}) __p += '\\n\\n") + 28);
    source = source.substring(0, source.indexOf("\\n\\n';"));
    
    // Reverse escape
    source = source.replace(/' \+ \(null == \(__t = ([^)]+)\) \? "" : _.escape\(__t\)\) \+ '/g, "<%- $1 %>");
    
    $('#result').text(source.replace(/\\n/g, "\n"));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
    <pre id="result"/>