How to pass variables into an HTML body

前端 未结 2 1298
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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, :

    
    

    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

    
    
    Calories
    Calories From Fat
    PolyUnsaturated

提交回复
热议问题