/* sprinth( format_string, hash )
Replace %{foo} templates with hash["foo"] with proper escaping. hash may
also be a prototype.js extended hash.
%% literal %
%{} HTML-escape replaces &, <, and > with &, <, and >
%[] JavaScript-escape replaces \, ", and ' with \\, \", and \'
%<> URI-escape uses core encodeURIComponent() function
%«» URI-escape uses core encodeURI() function [leaves , / ? : @ & = + $ # alone]
%() unescaped inserts hash value with no substitutions
Escaping may be nested, for instance: %{[foo]} will js-escape then HTML escape the hash value.
Example:
sprinth( '
%{foo}
',
{ foo: 'f\'(x) < 23', bar: '\'e said, ""' }
);
*/
// use prototype.js to escape if available (presumedly faster - makes only single pass)
function html_escape(str) {
if (str.toString)
str = str.toString();
if (str.escapeHTML)
return str.escapeHTML();
else
return str.replace(/&/g,'&').replace(//g,'>');
}
function js_escape(str) {
return str.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/'/g,'\\\'');
}
function _stringify(str) {
if (typeof str === "undefined" || str === null)
return '';
return str;
}
function _sprinth(fmt, h) {
var idx, func;
switch (fmt[0]) {
case "{": idx = fmt.indexOf("}",1); func = html_escape; break;
case "[": idx = fmt.indexOf("]",1); func = js_escape; break;
case "<": idx = fmt.indexOf(">",1); func = encodeURIComponent; break;
case "«": idx = fmt.indexOf("»",1); func = encodeURI; break;
case "(": idx = fmt.indexOf(")",1); func = function(e){return e}; break;
// unwrapped everything, fmt should be a key of h
default:
if (h.get)
return _stringify(h.get(fmt));
else
return _stringify(h[fmt]);
}
if (idx < 0) return fmt;// unbalanced bracketing
else return func(_sprinth(fmt.substr(1,idx-1),h)) + fmt.substr(idx+1);
}
function sprinth(fmt, h) {
var pieces = fmt.split('%');
var res = pieces[0];
for (var i = 1; i < pieces.length; i++) {
if (pieces[i] == "")
res += "%" + pieces[++i];
else
res += _sprinth(pieces[i], h);
}
return res;
}
/*
Author: Dean Serenevy : http://dean.serenevy.net/
This software is hereby placed into the public domain. If you use this
code, a simple comment in your code giving credit and an email letting me
know that you find it useful would be courteous but is not required.
The software is provided "as is" without warranty of any kind, either
expressed or implied including, but not limited to, the implied warranties
of merchantability and fitness for a particular purpose. In no event shall
the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising
from, out of or in connection with the software or the use or other
dealings in the software.
*/