Issue
I am using the Guardian API for a project to create a small News based web application to display content on a single page. I am mainly struggling with quoting in JavaScript when trying to write a function whithin a string. Based on the results the information should populate a card with the thumbnail, headline etc.
This is the script.
const GetNews = async (page) => {
console.log('Retrieving News Articles...')
var url = 'https://content.guardianapis.com/search?' +
' from-date=2023-01-01&' +
'to-date=2024-01-05&' +
'show-fields=trailText%2Cheadline%2Cthumbnail&' +
'page=' +page+
'&' +
'q=Sport&' +
[API Key]
var req = new Request(url);
let response = {"response":...}
console.log(response)
let str = ''
for (let item of response.results) {
str = str + '<div class="card my-4 mx-4" style="width: 20.5rem;">\
<img src= '${item.thumbnail}' class="card-img-top" alt="Card image cap">\
<div class="card-body">\
<h5 class="card-title">'${item.headline}'</h5>\
<p class="card-text">'${item.trailText}'</p>\
<a href="${item.webUrl}" target="_blank" class="btn btn-primary">Read More</a>\
</div>\
</div>'
}
I have tried different syntax but I don't know if I am writing it incorrectly, it is to be noted that I am relatively inexperienced with JavaScript.
From following videos I have seen people write these expressions normally and they appear a different colour to signify they are seperate from the quotes, but after researching I have read the $ operator can only be used with single quotes hence why I wrote the code this way.
Solution
You are on the right track. In JS, you can execute expressions and put them in strings like so:
console.log(`Function result: ${someFunction()}`);
There is one mistake in your syntax. You are using single quotes ('); you must use backticks (`) for strings using the "${}" syntax. Instead, use this:
str = str + `<div class="card my-4 mx-4" style="width: 20.5rem;">\
<img src= `${item.thumbnail}` class="card-img-top" alt="Card image cap">\
<div class="card-body">\
<h5 class="card-title">${item.headline}</h5>\
<p class="card-text">'${item.trailText}'</p>\
<a href="${item.webUrl}" target="_blank" class="btn btn-primary">Read More</a>\
</div>\
</div>`
These strings are called Template Literals
. Learn more on this topic at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.
Answered By - Python Nerd
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.