如何让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>
原理说明
- 子模板解析:修改
include函数后,引入的文件不再是静态HTML,而是被创建为HtmlTemplate实例,调用evaluate()会解析其中的<?模板语法。 - 变量共享:通过
Object.assign(subTemplate, this),主模板中定义的所有变量(比如title、otherVar)都会被复制到子模板中,子页面可以直接使用这些变量。 - 合法变量名:JavaScript不允许变量名包含减号,必须使用驼峰命名、下划线命名等合法格式,否则会触发语法错误。
内容的提问来源于stack exchange,提问作者klewis
相关产品推荐
相关产品推荐

