【问题标题】:How to use scriptlets in HTMLOutput in Google Apps Script如何在 Google Apps 脚本的 HTMLOutput 中使用 scriptlet
【发布时间】:2015-02-15 03:09:44
【问题描述】:

我正在加载一个模态对话框:

 var html = HtmlService.createHtmlOutputFromFile('File')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
    .setWidth(1000)
    .setHeight(700);

 SpreadsheetApp.getUi() 
    .showModalDialog(html, 'My Page');

现在,在 File.HTML 中,我想加载另一个带有 CSS 设置的 HTML 文件,我该怎么做?

我尝试使用 scriptlet 将它包含在 HtmlTemplate 中,但它不起作用:

<?!= include('File'); ?>

编辑:

我已经在code.gs中定义了include函数:

function include (file) {
  return HtmlService.createTemplateFromFile(file).evaluate().getContent();
}

【问题讨论】:

    标签: html google-apps-script web-applications


    【解决方案1】:

    问题是你正在使用:

    createHtmlOutputFromFile
    

    代替:

    createTemplateFromFile
    

    你需要创建一个模板:

    这就是你所看到的:

    scriptlet 未运行,但被解释为文本。

    这是你想看到的:

    代码应该是这样的:

    代码.gs

    // Use this code for Google Docs, Forms, or new Sheets.
    function onOpen() {
      SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
          .createMenu('Dialog')
          .addItem('Open', 'openDialog')
          .addToUi();
    }
    
    function openDialog() {
      var html = HtmlService.createTemplateFromFile('index')
        .evaluate();//This is necessary
    
        SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
        .showModalDialog(html, 'Dialog title');
    }
    
    function include(File) {
      return HtmlService.createHtmlOutputFromFile(File).getContent();
    };
    

    index.html

    <?!= include('File'); ?>
    
    Hello, world!
    <input type="button" value="Close"
      onclick="google.script.host.close()" />
    

    文件.html

    <div>
        This is a test. it worked!
    </div>
    

    基本上,你需要改变:

    var html = HtmlService.createHtmlOutputFromFile('index')
    

    到:

    var html = HtmlService.createTemplateFromFile('index')
    

    从文件中创建一个模板

    我还把代码改成了这样:

    function openDialog() {
      var html = HtmlService.createTemplateFromFile('index')
        .evaluate()
        .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    

    原答案:

    include 不像 keyword 或内置函数。您需要在名为include.gs 脚本文件中创建一个函数。

        function include(filename) {
          return HtmlService.createHtmlOutputFromFile(filename).getContent();
        };
    

    此外,您不能混合使用 HTML 服务和 UI 服务。我不知道这是否是你想要做的,但我想我会提到它。

    您想要完成的内容在此处的文档中进行了描述:

    Documentation - Best Practices

    【讨论】:

    • 谢谢,请看我的编辑。我之前在 code.gs 中定义了 include。它在侧边栏中运行良好,但是当我打开模式对话框时,它只键入 != include('File'); ?>
    • 是的,这也适用于新的 IFRAME 模式。必须更好地理解模板和输出之间的区别
    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多