javascript - 使用 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>...'
但这只是用标签写字符串。
解决方案
您需要items
使用标准脚本循环:
<? for(const item of items){?>
<div>
<div><?= item.name ?></div>
<div><?= item.age ?></div>
<div><?= item.address ?></div>
</div>
<? } ?>
推荐阅读
- c++ - 从 'pthread_t' 到 'pthread_t* {aka long unsigned int}' 到 'pthread_t* 的 C++ 无效转换
- c++ - 嗨... id_public 变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- visual-studio-code - 编译时未定义对“WinMain@16”的引用
- javafx - JavaFX 模块 javafx.graphics
- json - Firebase 通知在我自己的设备上不起作用
- c# - 使用 IClientModelValidator 在 ASP.NET Core 中使用参数自定义客户端验证属性
- android - 在 Android 中实现自定义日视图
- flutter - Flutter Theme FlatButton textColor in ButtonBar
- vala - Vala:在构造函数中调用超类创建方法
- javascript - 在 React / Redux 中,如何在 componentDidMount 中调用两次相同的 fetch,设置 2 个状态变量和结果