Thursday, 5 July 2012

JSRender Rocks!

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":}));
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":}));
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":}));
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":}));

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:


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 class="row-fluid thing">
            <div class="span6"><strong>Company:</strong></div>
            <div class="span6 company">{{>company}}</div>
        <div class="row-fluid thing">
            <div class="span6"><strong>Street:</strong></div>
            <div class="span6 street">{{>street}}</div>
        <div class="row-fluid thing">
            <div class="span6"><strong>Town:</strong></div>
            <div class="span6 town">{{>town}}</div>
        <div class="row-fluid thingBottom">
            <div class="span6"><strong>Phone:</strong></div>
            <div class="span6 phone">{{>phone}}</div>

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