I have a Google Apps Script WebApp that automates emails for particular events with webhooks.
I have an array of objects which i need to map to the html template file in the same directory.
For example, my Code.gs file looks like this:
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: '[email protected]',
subject: 'This is an automated email',
htmlBody: template.evaluate().getContent()
})
}
}
And the my-template.html file looks like this:
<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>
I have tried using script tags in the html file but they don't seem to be being executed, probably because its emailed.
I have also tried to map each item to a string and pass the string to the html like this:
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>...'
But that just writes the string with the tags.
htmlBody: "<body>" + items.reduce((s, e) => (s += "<div>" + Object.entries(e).map(([,f]) => "<div>" + f + "</div>").join("") + "</div>"), "") + "</body>"? - Tanaike