Hellnar
Hellnar

Reputation: 64803

A better way of generating HTML via Jquery

I feel my approach is unreadable and looks ugly for generating a list of items from a JSON object and adding it to an existing div.

my html:

<ul id='to-be-filled'> </ul>

my javascript

myJson = [
    {
        "title": "First",
        "action": "1st"
    },
    {
        "title": "Second",
        "action": "2nd"
    },
    {
        "title": "Third",
        "action": "3rd"
    }
]


function genList(){
var outputList = '';

$.each(myJson, function() { 
  outputList += '<li>' + this.title + ': ' + this.action + '</li>'
});

$('#to-be-filled').html(outputList); //set the generated html string.
}

$(document).ready(function() {
  genList(); //init
});

Result is here: http://jsfiddle.net/GxdA6/

How can I improve this mess of appending html string, especially my real code has more complex DOM and JSON data structure?

Upvotes: 2

Views: 124

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074435

If you need to do a lot of this client-side, I'd look at using templates. That plug-in is currently in beta and so it's subject to change, but I think the basics of it are pretty well set. Or you could use another templating plug-in for jQuery, there are several out there. My main message isn't "use jQuery templates" so much as "use templates". :-)

But that specific plug-in is coming along and has some major muscle behind it. There are two different ways you can define the template: Either by including it in your document as a script element:

<script id="your-li-template" type="text/x-jquery-tmpl">
    <li>${title}: ${action}</li>
</script>

...which you then retrieve and use like this:

var t = $("#your-li-template");
var outputList = t.tmpl(myJson);

Live example

Or you can define it in your JavaScript code as a string, and then use it slightly differently (this difference is, I suspect, one part of why it's still in beta):

// Compile it once
var t = $.template("<li>${title}: ${action}</li>");

// Use it as often as you need
var outputList = $.tmpl(t, myJson);

Live example

In both cases, apparently (from the examples) if you give it an array, it will repeatedly evaluate each item in the array against the template, so you don't even have to loop.

Upvotes: 4

jfriend00
jfriend00

Reputation: 707416

Here's a different version that uses an array instead of an object. Sometimes I find the object is just so much more cluttered than an array that has implicit field positions. You can decide which one makes more sense to you:

myJson = ["First", "1st", 
         "Second", "2nd", 
         "Third", "3rd"];

function genList(){
    var outputList = '';

    for (var i = 0; i < myJson.length; i++) { 
          outputList += '<li>' + myJson[i++] + ': ' + myJson[i] + '</li>'
}

$('#to-be-filled').html(outputList); //set the generated html string.
}

$(document).ready(function() {
  genList();
});

jsfiddle: http://jsfiddle.net/jfriend00/Fgx4V/

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47988

I've read a number of things that suggest that you shouldn't use string concatenation when you're doing this type of thing. Instead, something like this tends to net significant performance improvements, especially with large numbers of elements:

var toAdd = [], i = -1;

$.each(myJson, function () {
  toAdd[++i] = '<li>';
  toAdd[++i] = this.title;
  toAdd[++i] = ': ';
  toAdd[++i] = this.action;
  toAdd[++i] = '</li>';
});

$('#to-be-filled').html(toAdd.join(''));

Whether or not that qualifies as "cleaner" is a tough call. I've personally become accustomed to the syntax and find it pretty easy to deal with, but it's 6's. The performance is definitely there though; I can vouch for using this approach to add hundreds of elements efficiently without running into time outs or browser hangs.

Upvotes: 0

Santiago
Santiago

Reputation: 2320

Mustache seems a good template alternative http://mustache.github.com/, you can use it on javascript and server side scripting, so you only have to learn one template system for all you web code.

Upvotes: 0

Related Questions