You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Google Apps Script中所有包含页面支持<?语法?

解决方案

问题出在你的include函数上——当前它只是读取文件的静态HTML内容,没有将引入的文件当作模板来解析,所以子页面里的<?语法无法生效。同时注意:JavaScript变量名不能包含减号,other-var是非法的变量名,需要改成otherVar或other_var这类合法命名。

修改后的代码

code.js

function doGet(e) {
  var tmp = HtmlService.createTemplateFromFile("mpage");
  tmp.title = "My Custom Title";
  tmp.otherVar = "我的自定义子页面变量"; // 使用合法变量名
  return tmp.evaluate();
}

function include(filename) {
  // 将引入的文件创建为模板实例
  var subTemplate = HtmlService.createTemplateFromFile(filename);
  // 把主模板的所有变量复制到子模板,让子模板能访问这些变量
  Object.assign(subTemplate, this);
  // 解析子模板并返回HTML内容
  return subTemplate.evaluate().getContent();
}

page-body.html

<main>
    <p>how can I render another variable like this, from this page?</p>
    <h3><?= otherVar; ?></h3> <!-- 修正为合法变量名 -->
</main>

原理说明

  1. 子模板解析:修改include函数后,引入的文件不再是静态HTML,而是被创建为HtmlTemplate实例,调用evaluate()会解析其中的<?模板语法。
  2. 变量共享:通过Object.assign(subTemplate, this),主模板中定义的所有变量(比如title、otherVar)都会被复制到子模板中,子页面可以直接使用这些变量。
  3. 合法变量名:JavaScript不允许变量名包含减号,必须使用驼峰命名、下划线命名等合法格式,否则会触发语法错误。

内容的提问来源于stack exchange,提问作者klewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:22:39