How to pass variables into an HTML body

前端 未结 2 1299
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 06:07

I have created this script that allows me to select a certain food item and the serving size and then it calculates nutritional value, adds it to a database, sums it all at the

相关标签:
2条回答
  • 2021-01-24 07:00

    The HTML must be a string (text), and you need to build the HTML with a text formula. Text strings in JavaScript are put together, (concatenated) with a plus sign:

    var tableHTML = '<table style="width:100%">' + //Note single quotes on ends
       "<tr><td>Calories</td><td>" +
       calories + 
       "</td></tr>" +
       "<tr><td>Calories From Fat</td><td>" + 
       caloriesFromFat + 
       "</td></tr>" +
       "<tr><td>PolyUnsaturated</td><td>" + 
       polyFat + 
      "</td></tr>" +
       "</table>";
    

    If double quotes are used in the HTML attribute, then use single quotes on the ends of the string. Then just use the variable name for the email HTML:

    htmlBody: tableHTML
    
    0 讨论(0)
  • 2021-01-24 07:04

    You can accomplish this elegantly with Printing Scriptlets, assuming your email HTML body is in a separate file within your project.

    Here's a printing scriptlet to insert the value of calories. Note the syntax encloses the variable name in a special tag, <?= ?>:

    <?=calories?>
    

    To fill out the template, use the HtmlService to get the template first, then treat the variables inside the printing scriptlets as object properties of the template.

    // get email template
    var template = HtmlService
          .createTemplateFromFile('email');
    
    // assign values to template printing scriptlets
    template.calories = totals[0][25];
    template.caloriesFromFat = totals[0][26];
    template.polyFat = totals[0][27];
    

    Final code

    Code.gs:

    // Get my email address
    var me = Session.getActiveUser().getEmail();
    
    // get email template
    var template = HtmlService
          .createTemplateFromFile('email');
    
    // assign values to template printing scriptlets
    template.calories = totals[0][25];
    template.caloriesFromFat = totals[0][26];
    template.polyFat = totals[0][27];
    
    // evaluate template to generate HTML
    var htmlBody = template.evaluate();
    
    //Sends email with summary
    MailApp.sendEmail({
      to: me,
      subject: "Daily Intake Log",
      htmlBody:  htmlBody
    });
    

    email.html

    <!-- HTML Email body with printing scriptlets -->
    <table style="width:100%">
      <tr>
        <td>Calories</td>
        <td><?=calories?></td>
      </tr>
      <tr>
        <td>Calories From Fat</td>
        <td><?=caloriesFromFat?></td>
      </tr>
      <tr>
        <td>PolyUnsaturated</td>
        <td><?=polyFat?></td>
      </tr>
    </table>
    
    0 讨论(0)
提交回复
热议问题