Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars - Decompile handlebars compiled code to handlebars template

Is it possible to decompile Handlebars precompiled code to Handlebars template?

Possibly convert something like this:

function program2(depth0, data) { var buffer = '', stack1; data.buffer.push('<div '); ...... data.buffer.push('</div></div>'); return buffer; }

to

<div>{{name}}</div>
like image 623
Bhoomi Avatar asked Jul 03 '14 05:07

Bhoomi


People also ask

How do I compile Handlebars templates?

Getting started Next, install the Handlebars npm package, which contains the precompiler. Create a file name example. handlebars containing your template: Handlebars <b>{{doesWhat}}</b> precompiled!

Is Handlebars a template language?

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

Is handlebar a template engine?

Handlebars is a logic-less templating engine that dynamically generates your HTML page. It's an extension of Mustache with a few additional features.


1 Answers

Unfortunately, there is currently no built-in way to do so.

One solution would be to write a function that traverses the compiled code, look for where the HTML is being pushed and then put that HTML back together (reverse engineer the function, essentially).

There's one drawback: the compiled templates use the depth0 variable to store the passed in from your model/object. You can see that and the other objects being passed in as parameters where each compiled template is being instantiated, IE::

App.Templates = function (Handlebars, depth0, helpers, partials, data) { ... }

So you would have to follow how each piece of HTML is rendered and find the variable names that correspond to the expressions where they are pushed in as the stack variables. You'd need to get the name of the variable used so you can add back the attribute of each Handlebars block in the template (ie: {{myData}}) as well as the expression used (and if it is a block expression).

Say I have a simple template:

{{#if stuff}}
    <div id="General" class="content-section">
    <p>{{myData}}</p>
    </div>
{{/if}}

The depth0 object would contain stuff and myData. They're being used inside of the template like so (this is not a working example, I edited a template to show you what it'd look like):

buffer += "\r\n\r\n<div id=\"General\" class=\"content-section\">\r\n"
    + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.stuff)),
    stack1 == null || stack1 === false ? stack1 : stack1.myData)), 
    typeof stack1 === functionType ? stack1.apply(depth0) : stack1))

Hopefully that helps a bit - it is certainly doable if you want to put the work in.

like image 159
code4coffee Avatar answered Nov 15 '22 10:11

code4coffee