Passing js Variable to html file GAS - BASIC

我们两清 提交于 2019-12-30 10:38:07

问题


I'm trying to pass a variable (my name in cell A1) from my code.gs to my Index.html and email it.

Can someone please tell me what I'm doing wrong or point me in the right direction.

Code.gs

function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}

function sendEmail() {
var ss = SpreadsheetApp.openById('MY_SPREADSHEET_ID');
var sheet = ss.getSheetByName('Sheet1');

var myName = sheet.getRange(1,1).getValue();

var template = HtmlService.createTemplateFromFile('Index');
var body = template.evaluate().getContent();

// SEND THE EMAIL
MailApp.sendEmail({
  subject:"Test Email",
  to:"example@domain.com",
  htmlBody: body,
});

return myName;

Index.html

<!DOCTYPE html>

<html>  
  <body>
  <p><? var data = sendEmail(); ?><?= data ?></p>
  </body>
</html>

回答1:


Read this, pushing variables to templates

 function doGet() {
    return HtmlService.createHtmlOutputFromFile('Index');
    }

    function sendEmail() {
    var ss = SpreadsheetApp.openById('MY_SPREADSHEET_ID');
    var sheet = ss.getSheetByName('Sheet1');

    var myName = sheet.getRange(1,1).getValue();

    var template = HtmlService.createTemplateFromFile('Index');
    template.data = myName;
    var body = template.evaluate().getContent();

    // SEND THE EMAIL
    MailApp.sendEmail({
      subject:"Test Email",
      to:"example@domain.com",
      htmlBody: body,
});

Index.html

<!DOCTYPE html>

<html>  
  <body>
  <p><strong><?= data ?></strong></p>
  </body>
</html>



回答2:


The question was still open when I found it and I had a similar problem, so here is my solution (without doGet()), based on the useful comments from Wim den Herder and Rubén (and the example in the documentation):

Code.gs

function sendEmail() {
var recipient = 'test@mail.de';
var subject = 'Test Email'; 
var message =     HtmlService.createTemplateFromFile('Index').evaluate().getContent();;


// SEND THE EMAIL 
GmailApp.sendEmail(
      recipient,         
      subject,                            
      message, {                        // body
      htmlBody: message                 // advanced options
    });

}

function getData(){
var ss = SpreadsheetApp.openById('MySpreadSheetId');
var sheet = ss.getSheetByName('Sheet1');
// Data is in cell A1
var myName = sheet.getRange(1,1).getValue();
return myName
}

Index.html

<!DOCTYPE html>

<html>  
  <body>
  <p><strong><? var data = getData() ?><?= data ?></strong></p>
  </body>
</html>


来源:https://stackoverflow.com/questions/32431991/passing-js-variable-to-html-file-gas-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!