In the following example I am trying to render a list of posts (title, body and their tags):
const container = $('.container');
posts.forEach((post)=> {
container.append(
`<div>
<h2>${post.title}</h2>
<p>${post.body}</p>
<div>
${post.tags.map((tag) => {
`<span>${tag.name}</span>`
})}
</div>
</div>`)
});
The output however renders an extra comma between tags. I have tried to to outputting 'test' instead of the actual tag names as well as swapping the span tag for a different html tag, but the result is still the same.
I have tried to search for this issue, but haven't had any luck finding anyone else having this issue with template literals.
Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.
The ${} syntax allows us to put an expression in it and it will produce the value, which in our case above is just a variable that holds a string! There is something to note here: if you wanted to add in values, like above, you do not need to use a Template Literal for the name variable.
Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.
Tagged templates. A more advanced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
That's exactly how Array.join() works by default (which is called when implicitly stringifying an array), adding a comma between array entries - which is what is returned by map() -> an array. You can easily get rid of it by calling it yourself, passing an empty string as argument to join()
${post.tags.map((tag) => `<span>${tag.name}</span>`).join('')}
Note that you would need to return from map too...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With