简体   繁体   中英

Javascript template literals - function call

I would like to know if is possible to call function inside a javascript template literals. For those who does not know https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals I have something like this:

`<div class="product-card-labels">
    ${statuses.forEach(function(status) { return `<span class="product-card-label">${status.name}</span>` })}
</div>`

As you can see I would like to call array.forEach() which should return string to the template.

You have the template syntax right, but are not returning anything in your function call. If you use .map and .join the output (instead of .forEach which returns undefined ), it'll work fine.

`<div class="product-card-labels">
    ${statuses.map(function(status) { return `<span class="product-card-label">${status.name}</span>`; }).join('')}
</div>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM