将变量从 .gs 共享到 Google Apps 脚本中的 .html

Share variable from .gs into .html in Google Apps Script

我正在尝试让 Google 表单调查的受访者填写另一份调查,但他们的一些答复将根据第一份调查预先填写。基本上,希望他们的所有回答都附在唯一的人身上,而不是让他们再次回答相同的问题。而且必须是两次调查,而不是连续调查。 在这个例子中,我只预填了他们的电子邮件地址,但可能会有更多字段。

所以在 Google Apps 脚本中,我有一个 Code.gs 和 Email1.html 脚本如下:

function confirmationEmail1(e) {
  
  var htmlBody= HtmlService.createHtmlOutputFromFile('Email1').getContent();
  var recipient=e.response.getRespondentEmail();
  if(recipient!==undefined){
    MailApp.sendEmail({
      to:recipient,
      subject: 'Thank you. Please answer another one',
      htmlBody: htmlBody,
    })
  }
}

以及以下电子邮件正文:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <p>Thank you for filling the survey</p> 
    <p>Now fill another one. Some answers will be pre-filled based on your past responses<p> 
    <p>To continue click this <a href="https://docs.google.com/forms/d/e/1FAIpQLSfqYWf-V0Jrwh8ld2AjuHtskuEHr1CfQB3_wrLS7grzZ_EajQ/viewform?usp=pp_url&entry.786833434=<?= recipient ?>">Link</a></p>
  </body>
</html>

我在这个地方做错了什么,它没有从 Code.gs 中检索收件人变量,而是在我的第二次调查中简单地预填了文本“”?

由于 htmlBody 是一个字符串,您可以使用 string.replace() 方法将任何文本片段替换为另一个文本片段。

假设您可以在 html:

中制作 {RECEPIENT}
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <p>Thank you for filling the survey</p> 
    <p>Now fill another one. Some answers will be pre-filled based on your past responses<p> 
    <p>To continue click this <a href="https://docs.google.com/forms/d/e/1FAIpQLSfqYWf-V0Jrwh8ld2AjuHtskuEHr1CfQB3_wrLS7grzZ_EajQ/viewform?usp=pp_url&entry.786833434=<?={RECEPIENT}?>">Link</a></p>
  </body>
</html>

然后将文本 {RECEPIENT} 替换为脚本中的 recepient 值:

function confirmationEmail1(e) {
  
  var htmlBody= HtmlService.createHtmlOutputFromFile('Email1').getContent();
  var recipient=e.response.getRespondentEmail();
  if(recipient!==undefined){

    htmlBody = htmlBody.replace('{RECEPIENT}', recipient); // <--- here

    MailApp.sendEmail({
      to:recipient,
      subject: 'Thank you. Please answer another one',
      htmlBody: htmlBody,
    })
  }
}