JQuery template () for placing url in src = image attribute
I have a jquery template:
<div id="test_template">
<img src="${url}" width="31" height="32" alt="" />
${url}
</div>
I will compile it with this:
test_template = $('#test_template').template();
I am doing this with this:
$.tmpl(test_template, {url:'http://sstatic.net/stackoverflow/img/sprites.png'}).appendTo('#render_test');
The end result is as follows:
<div id="render_test">
<img height="32" width="31" alt="" src="$%7Burl%7D"> http://sstatic.net/stackoverflow/img/sprites.png</div>
obviuosly I expected the url to be in the src = "tag ... but it is not (although after the tag is displayed it is correctly displayed). if I look at the anonymous function created by template (), I see that it is not turns src = "$ {url}" into javascript. it just encodes it as HTML and spits it back
what am I doing wrong?
+3
3 answers
I fix this with an ugly hack that uses TmplItem:
function fixRenderedTemplate(rendered){
var fixArray = [["img", "src"], ["a", "href"]];
for (var i=0; i<fixArray.length; i++){
var tagName = fixArray[i][0];
var attrName = fixArray[i][1];
$(tagName, rendered).each(function(index, elem){
var data = $(elem).tmplItem().data;
var fixTemplate = unescape($(elem).attr(attrName));
var url = $.tmpl(fixTemplate, data).text();
$(elem).attr(attrName, url);
});
}
return rendered
}
Just call the function on the template you created
0