【问题标题】:How to create resuable showModalDialog() in Google App Script?如何在 Google App Script 中创建可重用的 showModalDialog()?
【发布时间】:2019-11-30 06:43:40
【问题描述】:

我有 ModalDialog 提示用户选择日期范围以生成适当的信息。我有几个使用相同提示的菜单项,所以我想重用 ModalDialog。

// Available method
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Options for Menu Item N');

// What I hope is available
SpreadsheetApp.getUI().showModalDialog(htmlOutput, 'Options for Menu Item N', userdataN); // pseudocode
// inside HTML
var userdata = Script.host.environment // pseudocode do something with userdata in HTML

但是,showModalDialog() 函数不允许我将任何用户数据传递给 html,因此我无法确定需要将用户选择返回到哪个菜单项。

在这种情况下如何创建可重用的 ModelDialog?

编辑: 我意识到我可以在工作表中写入环境变量值,然后从 HTML 中检索该值,但是有没有更简洁的方法呢?

【问题讨论】:

标签: google-apps-script google-sheets


【解决方案1】:

您可以将用户数据对象作为 HtmlTemplate 对象的属性传递并使用 scriptlet 语法(请参阅this answer)或进行字符串插值。就个人而言,我更喜欢后一种选择,而不是使用 Google 的内置模板引擎。它更慢但更灵活。

假设我们在脚本编辑器中有一个名为“app”的 HTML 页面

  <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>{{global.app}}</h1>
    <div id=container>
      <ul>
        <li>{{name}}</li>
        <li>{{email}}</li>
        <li>{{age}}</li>
      </ul>
      Created by {{global.author}}.
    </div>
  </body>
</html>

您可以调用 HtmlService 方法将模板作为字符串提供。

 //serve HTML template as a string
function getTemplateAsString(filename) {
return HtmlService.createTemplateFromFile(filename).getRawContent();    
}

然后您可以将 html 字符串传递给插值函数:

var config = {
     app: "My app",
     author: "me"
   };

function interpolateString(htmlString, params) {

    //Add global variables to the template
  for (var configKey in config) {
    if (config.hasOwnProperty(configKey)) {
      htmlString = htmlString.replace("{{global." + configKey + "}}", config[configKey]);
    }
  }

  //Insert page-specific parameters
  for (var paramsKey in params) {
    if (params.hasOwnProperty(paramsKey)) {
      htmlString  = htmlString.replace("{{" + paramsKey + "}}", params[paramsKey]);
    } 
  }

  return htmlString;

}

对于最后一步,您从结果字符串创建 HtmlTemplate 对象并在其上调用“evaluate()”方法。调用 evaluate 会返回一个有效的 HtmlOutput 对象实例,您可以将其传递给 UI 方法

var template = HtmlService.createTemplate(htmlString);
ui.showModalDialog(template.evaluate(), "My dialog");

【讨论】:

  • 这是一个肮脏的好主意!在将此标记为答案之前,我将等待几天看看是否有更好的方法。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多