The right way to create a list of articles using jQuery

My first question is here at SO :). I really need to load the data as an array of such objects:

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 these codes good? Or is there (is) a better and more elegant way to build HTML?

Thanks!

+4
source share
2 answers

Thanks for answers. I ended up using Mustache.js to improve my codes. Thanks to Murali for the jQuery template link, which led me to further explore some of the available HTML templates. The reason I didn't go for jQuery templates was because it was discontinued and it no longer receives support from the jQuery team.

+2
source

use jTemplates .

or

format the template string with string.format

0
source

Source: https://habr.com/ru/post/1469151/


All Articles