Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNick Trabue
Courses Plus Student 12,666 PointsWhat am I doing wrong with template literals?
So I was really excited to start playing with template literals and I wanted to apply it to a project that I'm currently working on. I'm relatively new at Javascript so it's probably something really simple that I'm missing.
This was what I had and it worked:
for (var i=0; i<salesList.length; i++ ){
loListing += '<div class="thumbnail text-center">'
loListing += '<a href="'+salesList[i].lo_url+'"><img src="../'+salesList[i].lo_img+'" class="img-responsive" alt="Click to apply with '+salesList[i].lo_first_name +' '+ salesList[i].lo_last_name+'">'
loListing += '<div class="caption">'
loListing += '<p id="lo-caption">'+salesList[i].lo_first_name +' '+ salesList[i].lo_last_name+'</p>'
loListing += '<p id="lo-link">Apply with '+salesList[i].lo_first_name+'</p>'
loListing += '</div>'
loListing += '</div>'
}
This is what I tried using template literals. It only pulls the last object in the salesList array. The console log was just there for some troubleshooting but it does list all of the objects in the salesList array as expected:
for (let i=0; i<salesList.length; i++){
console.log(salesList[i]);
loListing = `
<div class="thumbnail text-center">
<a href="${salesList[i].lo_url}">
<img src="../${salesList[i].lo_img}" class="img-responsive" alt="Click to apply with ${salesList[i].lo_first_name}!">
<div class="caption">
<p id="lo-caption">${salesList[i].lo_first_name} ${salesList[i].lo_last_name}</p>
<p id="lo-link">Apply with ${salesList[i].lo_first_name}</p>
</div>
</div>
`
}
Thanks!
2 Answers
Steven Parker
231,269 PointsThe templates are working fine.
But each time through the array, you re-assign loListing, replacing anything already in it. So when the loop finishes, it will contain only the last item.
Did you intend to append to it instead, as you were doing in the earlier version? ("loListing +=
...")
Tomasz Cysewski
2,736 Pointsamazing code, I wish you good luck
Nick Trabue
Courses Plus Student 12,666 PointsNick Trabue
Courses Plus Student 12,666 PointsThank you, Steven. Every time through the loop it was resetting the loListing variable until it got to the last person in the loop. That makes perfect sense.