如何在Google Apps脚本中的HTMLOutput中使用scriptlet

时间:2014-12-16 17:52:12

标签: html google-apps-script

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

 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();
}

1 个答案:

答案 0 :(得分:8)

这就是你所看到的:

Include with Dialog

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

这是你想看到的:

Include that works

我得到了它的工作。以下是您需要更改代码的方法:

Code.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() // evaluate MUST come before setting the NATIVE mode
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);
    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()" />

File.html

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

基本上,您需要更改:

var html = HtmlService.createHtmlOutputFromFile('index')

为:

var html = HtmlService.createTemplateFromFile('index')

从文件中创建 TEMPLATE

我还将代码更改为:

function openDialog() {
  var html = HtmlService.createTemplateFromFile('index')
    .evaluate() // evaluate MUST come before setting the NATIVE mode
    .setSandboxMode(HtmlService.SandboxMode.NATIVE);

原始答案:

include不是keyword或内置函数。您需要在名为.gs的{​​{1}}脚本文件中创建一个函数。

include

此外,您无法混合HTML服务和UI服务。我不知道你是不是想做什么,但我想我会提到它。

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

Documentation - Best Practices