简体   繁体   中英

pass google script object to html template

I working on standalone web app in google script using HtmlService. Here's the part of code:

script:

function doGet() {
 getLabelsLists();
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate().setSandboxMode(HtmlServi‌​ce.SandboxMode.NATIVE);
}

function getEmails() {
  var query = ...;
  var threads = GmailApp.search (query);
  return threads;
} 

index.html:

<? var data = getEmails(); ?>
<table>
  <? for (var i = 0; i < data.length; i++) { 
  var message = data[i].getMessages()[0];
  ?>
    <tr onclick= click(<?= message.getId() ?>)>
        <td><?= message.getSubject() ?></td>
    </tr>
  <? } ?>
</table>

What I want to do is show only button like below on page load and on click call function that render table with a results.

 <input type="button" onclick="google.script.run.getEmails()" />

Any ideas how I can pass the array of gmail threads from getEmails() function to the view and dynamically create table?

You cannot pass such object (with function and custom prototype), only "simple" ones (composed of strings, numbers, booleans and arrays or objects containing those), like stated in the documentation . Therefore you'll have build an object with the values you need in order to pass it. Taking your usage example of getting the id and subject of only the first message in the threads, here's how it's done:

function getEmails() {
  var query = "...";
  return GmailApp.search(query).map(function(thread) {
    var msg = thread.getMessages()[0];
    return {id:msg.getId(), subject:msg.getSubject()};
  }
}

Then, to "read" the values, you should access id directly, instead of calling getId() , and subject , instead of getSubject() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM