I need to build HTML from an jQuery ajax response. I don't like nesting ugly strings in javascript and I don't want to use mustache or any other templating script.
So I went for the approach of having a template HTML with display: none like the following:
<div id="message-template" class="message-tile" style="display: none;">
<div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
<div class="message-data">
<div class="message-info">
<div class="sender-name">
<a href="{{person-url}}">{{person-name}}</a>
</div>
<div class="posted-to">
To <a href="{{posted-to-url}}">{{posted-to-title}}</a>
</div>
</div>
<div>{{message-body}}</div>
</div>
</div>
I want to be able to replace the strings between {{ }} with the actual values from the json object. Suppose this is the function that gets called on the jQuery.ajax onSuccess event:
function createNewElement(jsonObj) {
var $clone = $('#message-template').clone();
$clone.replaceString("{{person-name}}", jsonObj.personName);
$clone.replaceString("{{thumb-url}}", jsonObj.thumbUrl);
$clone.replaceString("{{person-url}}", jsonObj.personUrl);
// etc
$("#target-container").append($clone);
}
I invented the replaceString method, but is there something similar? Or do I need to traverse through each element child using find() ?