Convert template from Handlebars to Mustache
function convertToMustache(str) { | |
var stack = [], | |
reg = /{{([#\/]?)(\w+)?\s?(..\/)?(\w+)?}}/g; | |
str = str.replace(reg, function (match, pre, helper, path, key) { | |
if (pre === '#') { | |
stack.push({ | |
type: helper, | |
key: key | |
}); | |
} | |
if (pre === '/') { | |
var obj = stack.pop(); | |
if (obj.type === helper) { | |
key = obj.key; | |
} else { | |
throw new Error('match error'); | |
} | |
} | |
if (helper === 'else') { | |
var obj = stack[stack.length - 1]; | |
return '{{/' + obj.key + '}}{{^' + obj.key + '}}'; | |
} | |
key = key || helper; | |
return '{{' + pre + key + '}}'; | |
}); | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment