简体   繁体   中英

How to loop through javascript variables inside a html block?

I'm trying to pass a html block to a email service Nodemailer JS function (I'm using Node.JS). I have an items array that needs to be sent in the email:

items = [ 
   { name: 'prod1', description: 'desc1', quantity: 666, price: 666.66 },
   { name: 'prod2', description: 'desc2', quantity: 555, price: 555.55 }
];

Here is the JS funcition. I'm using a <table> tag to put the elements of items array. I can put this html inside a JS variable before sending it to the function, but I'm not sure how to insert the items. How to make it work?

await email.sendEmail(user.email, 'Order confirmation',
      `<div style='text-align:center'>
      <p> Order Details </p> <hr>
      <table>
          <tbody>
              <tr>
                  <td> ${items} </td>
              </tr>
          </tbody>
      </table></div>`);

Build the string containing the HTML in a loop before the call:

var rows = items.map(({name, description, quantity, price}) =>
    `<tr><td>${name}</td><td>${description}</td><td>${quantity}</td><td>$${price}</td></tr>`).join('');
await email.sendEmail(user.email, 'Order confirmation',
      `<div style='text-align:center'>
      <p> Order Details </p> <hr>
      <table>
          <tbody>
              ${rows}
          </tbody>
      </table></div>`);

Iterate through items and build your html table

var itemHtml = `<div style='text-align:center'>
      <p> Order Details </p> <hr>
      <table>
          <tbody>`;
for(var i=0; i<items.length; i++){
  var item = items[i];
  itemHtml += `<tr>
     <td>${item.name}</td>
     <td>${item.description}</td>
     <td>${iten.quantity}</td>
     <td>${item.price}</td>
  </tr>`; 
}
itemHtml += `</tbody></table></div>`;

then use the variable in your email.

await email.sendEmail(user.email, 'Order confirmation', itemHtml);

something like this.

const listItems = items.map((item) =>
    <td>{item.name}</td>
    <td>{item.desc}</td>
    <td>{item.price}</td>
    );
  return (
    <tr>{listItems}</tr>
  );

You can use nested maps to loop through your items, and the properties of each item like so:

 items = [ { name: 'prod1', description: 'desc1', quantity: 666, price: 666.66 }, { name: 'prod2', description: 'desc2', quantity: 555, price: 555.55 } ]; var keys = Object.keys(items[0]) await email.sendEmail(user.email, 'Order confirmation', `<div style='text-align:center'> <p> Order Details </p> <hr> <table> <tbody> ${items.map(item => { return `<tr>${keys.map(key => { return `<td>${item[key]}</td>` }).join("")}</tr>` }).join("")} </tbody> </table></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