var newCustomer = $("<div></div>", {"class": "customer row-fluid", "data-id": data.msg}).appendTo($("#customers")); var newName = $("<div></div>", {"class": "row-fluid thingTop"}).appendTo(newCustomer); newName.append($("<div></div>", {"class": "span6"}).html("<strong>Name:</strong>")); newName.append($("<div></div>", {"class": "span6 name", "text": data.name})); var newCompany = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer); newCompany.append($("<div></div>", {"class": "span6"}).html("<strong>Company:</strong>")); newCompany.append($("<div></div>", {"class": "span6 company", "text": data.company})); var newStreet = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer); newStreet.append($("<div></div>", {"class": "span6"}).html("<strong>Street:</strong>")); newStreet.append($("<div></div>", {"class": "span6 street", "text": data.street})); var newTown = $("<div></div>", {"class": "row-fluid thing"}).appendTo(newCustomer); newTown.append($("<div></div>", {"class": "span6"}).html("<strong>Town:</strong>")); newTown.append($("<div></div>", {"class": "span6 town", "text": data.town})); var newPhone = $("<div></div>", {"class": "row-fluid thingBottom"}).appendTo(newCustomer); newPhone.append($("<div></div>", {"class": "span6"}).html("<strong>Phone:</strong>")); newPhone.append($("<div></div>", {"class": "span6 phone", "text": data.phone}));
So the above is what I used to do on a mates web application when she entered a new user to her system. I just knew there must be a better way though so I got to looking and looking and looking and saw something about jQuery Templates but then saw that they'd fallen out of favour. I think that that is a shame but they've been replaced with JsRender - which just rocks!
All of the code above ended up being replaced with this:
$("#customers").append( $("#addCustomer").render(data) );
Of course I had to add this to the base page:
<script id="addCustomer" type="text/x-render"> <div class="row-fluid customer" data-id="{{>id}}"> <div class="row-fluid thingTop"> <div class="span6"><strong>Name:</strong></div> <div class="span6 name">{{>name}}</div> </div> <div class="row-fluid thing"> <div class="span6"><strong>Company:</strong></div> <div class="span6 company">{{>company}}</div> </div> <div class="row-fluid thing"> <div class="span6"><strong>Street:</strong></div> <div class="span6 street">{{>street}}</div> </div> <div class="row-fluid thing"> <div class="span6"><strong>Town:</strong></div> <div class="span6 town">{{>town}}</div> </div> <div class="row-fluid thingBottom"> <div class="span6"><strong>Phone:</strong></div> <div class="span6 phone">{{>phone}}</div> </div> </div> </script>
But what the hey, at least I'm keeping my markup where it needs to be, on the page. Who cares if it's something of a fudge...? I dare say I will soon, but it'll do for now ;-)
No comments:
Post a Comment