4

My first question here in SO :). I actually need to load data in the form of array of objects like this:

var data = [
{
    'id': '1',
    'firstName': 'Megan',
    'lastName': 'Fox',
    'picture': 'images/01.jpg',
    'bio': 'bla bla bla bla.'
},
{
    'id': '2',
    'firstName': 'Robert',
    'lastName': 'Pattinson',
    'picture': 'images/02.jpg',
    'bio': 'bli bli bli bli.'
}

Then I would like to display the data in HTML using this structure:

<div class="wrapper">
    <article>
        <header>
            <h2>[firstName 1 here]<h2>
        </header>
        <section>
            <p>[bio 1 here]</p>
        </section>
    </article>
    <article>
        <header>
            <h2>[firstName 2 here]<h2>
        </header>
        <section>
            <p>[bio 2 here]</p>
        </section>
    </article>
</div>

And the JS function I created is below:

var loadArtists = function() {
    var $tmpHtml = '';
    for (var artist in artists) {
        var objArtist = artists[artist],
        fullname = objArtist.firstName + ' ' + objArtist.lastName,
        bio = objArtist.bio,
        id = objArtist.id,
        pic = objArtist.picture;

        $tmpHtml += '<article><header data-id="' + id + '"><h2>' + fullname + '</h2></header><section data-id="' + id + '"><div class="imgContainer"><img alt="' + fullname + '" src="' + pic + '" /></div><h2 class="hiddenName">' + fullname + '</h2><p>' + bio + '</p></section></article>'; 
    }

    $('div.wrapper').append($tmpHtml);
};

Are those codes good? Or there is (are) better and more elegant way to construct the HTML?

Thanks!

yovib
  • 96
  • 4

2 Answers2

2

Thanks for the answers. I ended up using Mustache.js to make my codes better. Thanks to Murali for the jQuery template link which led me to do more research on some of the available HTML template libraries. The reason I did not go for jQuery templates, because its been discontinued and it's not receiving anymore support from the jQuery team.

Dan D.
  • 67,516
  • 13
  • 93
  • 109
yovib
  • 96
  • 4
  • Mustache is great. You might also take a look at Handlebars (http://handlebarsjs.com/), which is Mustache-compatible. Want to know the differences? Stack Overflow to the rescue as always: http://stackoverflow.com/questions/10555820/what-are-the-differences-between-mustache-js-and-handlebars-js – Aurelio Jun 27 '13 at 00:44
  • 1
    Yes, I also used Handlebars apparently, so much better way to use HTML templating rather than the conservative way. Thanks for pointing that out. – yovib Oct 22 '13 at 23:37
0

use jTemplates.

or

format your template string using string.format

Community
  • 1
  • 1
Scy
  • 458
  • 2
  • 11