Created
June 29, 2018 21:19
-
-
Save goto-bus-stop/6d07f3b7666c5d18ce83f2b5164be908 to your computer and use it in GitHub Desktop.
take a compiled handlebars template function, return the source string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is a terrible hack, don't look at it god please don't look at it | |
function noop () {} | |
var makePlaceholder = function (name) { | |
function helper () { | |
var args = [] | |
for (var i = 0; i < arguments.length; i++) args.push(arguments[i]) | |
var opts = args.pop() | |
var out = '{{' | |
if (opts && opts.fn) out += '#' | |
else out += '{' | |
out += name | |
args.forEach(function (a) { | |
out += ' ' + (a + '').replace(/^\{{3}|\}{3}$/g, '') | |
}) | |
out += '}}' | |
if (opts && opts.fn) { | |
out += opts.fn() | |
out += '{{/' + name + '}}' | |
} else out += '}' | |
return out | |
} | |
Object.assign(helper, { | |
toString: function () { return '{{{' + name + '}}}' }, | |
toPrimitive: function () { return '{{{' + name + '}}}' } | |
}) | |
return new Proxy(helper, { | |
get: function (target, prop) { | |
if (typeof prop !== 'string') return target[prop] // symbols n shit | |
if (typeof target[prop] === 'function') return target[prop] // .call() n shit | |
return makePlaceholder(name + '.' + prop) | |
} | |
}) | |
} | |
var context = new Proxy({}, { | |
get: function (target, prop) { | |
if (typeof prop !== 'string') return target[prop] | |
return makePlaceholder(prop) | |
} | |
}) | |
module.exports = function handleback (template) { | |
return template.call({ | |
noop: noop, | |
program: function (type, block) { | |
return function () { | |
if (type === 1) return block() | |
// others? | |
throw new Error('unknown type') | |
} | |
}, | |
escapeExpression: function (a) { return a.replace(/^\{|\}$/g, '') }, | |
merge: function (a) { return a } | |
}, { helpers: null }, context, context) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
paste the function that is passed to
HandlebarsRuntime.template(FN)
intohandleback()
instead:output: