Created
July 27, 2017 13:10
-
-
Save kucaahbe/6d74a6ab0799a71be54dcf0f6df7eca8 to your computer and use it in GitHub Desktop.
simple javascript string template engine
This file contains hidden or 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
/** | |
Usage: | |
var engine = SimpleJsTemplator({ | |
value: '{pattern}' | |
}) | |
engine.compile('string with {pattern}', { value: 'PATTERN' }) | |
will produce: | |
'string with PATTERN' | |
*/ | |
var SimpleJsTemplator = (function () { | |
var Template = function (patterns) { | |
if ( $.isEmptyObject( patterns ) ) { | |
throw new Error('non-empty pattern list object required'); | |
} | |
var _matchTable = {}; | |
var regexps = []; | |
$.each(patterns, function (dataParam, templateValue) { | |
regexps.push('(' + escapeRegExp(templateValue) + ')'); | |
_matchTable[templateValue] = dataParam; | |
}); | |
this._pattern = new RegExp('(?:'+ regexps.join('|') +')', 'giu') | |
this._matchTable = _matchTable; | |
}; | |
Template.prototype.compile = function (string, data) { | |
var _matchTable = this._matchTable; | |
return string.replace(this._pattern, function (match) { | |
return data[_matchTable[match]]; | |
}); | |
}; | |
// src: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions | |
function escapeRegExp(string) { | |
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string | |
} | |
return Template; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment