jquery - Javascript templating function replace string and dont take care of whitespace -
i've written days ago simple templating function, problem whitespace kill tag. when type this: <div id="str">#{my} #{name} #{is} #{#{a}}</div>
works well, next not: <div id="str">#{my} #{name} #{is} #{ #{a} }</div>
.
here's i've done far:
$.tmpl = function(str, obj) { { var beforereplace = str; for(var key in obj) { str = str.replace("#{" + key + "}", obj[key]); } var afterreplace = str !== beforereplace; } while (afterreplace); homecoming str; }; var map = { my: "am", name: "i", is: "<a href='#'>awesome</a>", a: "#{b}", b: "c", c: "?" }; $("#str").html(function(index, oldhtml) { $(this).html( $.tmpl(oldhtml, map) ); });
how can working if utilize #{a}
, #{ #{a} }
. know, possible, , simple, not regexp pro.
this works.
this fails.
you need trim whitespace key you're replacing. this, can utilize function sec parameter string.replace() function. can replace matches each pass @ 1 time using function this. so, seek following:
$.tmpl = function(str, obj) { { var beforereplace = str; str = str.replace(/#{([^}]+)}/g, function(wholematch, key) { var substitution = obj[$.trim(key)]; homecoming (substitution === undefined ? wholematch : substitution); }); var afterreplace = str !== beforereplace; } while (afterreplace); homecoming str; };
the regexp /#{([^}]+)}/g finds occurrences (the "g" means "global") of string starts "#{", has @ to the lowest degree 1 character not "}", ends "}". parentheses serve grouping key regexp engine pull out parameter function.
the other regexp replacement (/^\s+|\s+$/g) trims string. finds leading , trailing whitespace , removes it. in ecmascript 5, there string.trim() function provides functionality built-in, not widespread plenty reliably utilize it. see mdn documentation details.
however, i'm not sure of wisdom of doing multiple passes this. introduce possibility of infinite looping:
var map = { a: "#{b}", b: "#{a}" }; $.tmpl("#{a}", map);
you introduce possibility values in map might accidentally contain #{...} , expanded without intending to. particularly worrisome if values entered user. in case, have given him possibility create app loop infinitely or expose values of other keys. template engines not provide ability repeatedly substitute parameters in fashion.
jquery regex replace template-engine str-replace
No comments:
Post a Comment