Created
May 14, 2011 13:19
-
-
Save narqo/972203 to your computer and use it in GitHub Desktop.
A simple javascript template language.
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
/** | |
* Движек шаблонов (template engine). | |
* | |
* Синтаксис: | |
* <code> | |
* var tpl = "Время ожидания ответа составило бы %{var} миллиардов лет", | |
* data = {var: 80}; | |
* te.renderTpl(tpl, data, 1); | |
* </code> | |
*/ | |
var te = { | |
// TODO: пред-компилировать шаблоны в стороку: <code>'some str' + data.foo + 'another str'</code> | |
// см. <code>offset</code> (<a>replace @ mdc</a>) | |
/** | |
* @param {String} tpl Шаблон | |
* @param {Object} context Контекст с данными для шаблона | |
* @param {String} [default_ = ''] Строка возвращаемая в случае ошибки рендера | |
* | |
* @return {String} | |
*/ | |
renderTpl: function(tpl, context, default_) { | |
var re = /%\{([-_0-9a-z\.]+)\}/gi, | |
matchFail = false, | |
def = default_ || ''; | |
if( !context ) { | |
return def; | |
} | |
var retStr = tpl.replace(re, function(m, key, offset, s) { | |
// Разбиваем ключ "по-точке" (".") для возможности использовать | |
// в шаблоне переменные вида ``%{foo.bar}`` | |
var keys = key.split('.'), | |
value = context; | |
for( var i = 0, k = keys.length; i < k; i++ ) { | |
var tplKey = keys[i]; | |
if( !value[tplKey] ) { | |
return (matchFail = true, ''); | |
} | |
value = value[tplKey]; | |
} | |
return value; | |
}); | |
return !matchFail ? retStr : def; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment