Skip to content

Instantly share code, notes, and snippets.

@meathill
Last active December 21, 2015 20:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save meathill/6361267 to your computer and use it in GitHub Desktop.
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