首页 > 解决方案 > 使用 Google Apps 脚本文件将项目映射到 html 文件

问题描述

我有一个 Google Apps Script WebApp,它使用 webhook 为特定事件自动发送电子邮件。

我有一个对象数组,我需要将它们映射到同一目录中的 html 模板文件。

例如,我的 Code.gs 文件如下所示:

function doThing() {
  if ('Some condtition' === true) {
    let template = HtmlService.createTemplateFromFile('my-template')

    let items = [
      { name: 'John Smith', age: 20, address: '123 fakestreet' },
      { name: 'Sam Smith', age: 27, address: '123 fakestreet' },
      { name: 'Phil Smith', age: 10, address: '123 fakestreet' }
    ]

    template.items = items

    MailApp.sendEmail({
      to: 'John@gmail.com',
      subject: 'This is an automated email',
      htmlBody: template.evaluate().getContent()
    })
  }
}

my-template.html 文件如下所示:

<body>
<!-- This is how to call the passed variable -->
    <?= items ?> 

    <!-- I want to map my items like this -->
    <div>
        <div>John Smith</div>
        <div>20</div>
        <div>123 fakestreet</div>
    </div>
    <div>
        <div>Sam Smith</div>
        <div>27</div>
        <div>123 fakestreet</div>
    </div>
    <div>
        <div>Phil Smith</div>
        <div>10</div>
        <div>123 fakestreet</div>
    </div>
</body>

我曾尝试在 html 文件中使用脚本标签,但它们似乎没有被执行,可能是因为它已通过电子邮件发送。

我还尝试将每个项目映射到一个字符串并将字符串传递给 html,如下所示:

let items = '<div>
        <div>John Smith</div>
        <div>20</div>
        <div>123 fakestreet</div>
    </div>
    <div>
        <div>Sam Smith</div>
        <div>27</div>
        <div>123 fakestreet</div>
    </div>...'

但这只是用标签写字符串。

标签: javascriptgoogle-apps-script

解决方案


您需要items使用标准脚本循环:

<? for(const item of items){?>
   <div>
        <div><?= item.name ?></div>
        <div><?= item.age ?></div>
        <div><?= item.address ?></div>
    </div>
<? } ?>

推荐阅读