Last active
December 21, 2015 20:29
-
-
Save meathill/6361267 to your computer and use it in GitHub Desktop.
Convert template from Handlebars to Mustache
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
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