【问题标题】:Passing object to template with Google Apps Script and HtmlService使用 Google Apps 脚本和 HtmlService 将对象传递给模板
【发布时间】:2012-12-14 17:48:37
【问题描述】:

所以我在 Google 电子表格中有一个植物列表,我想以 HTML 格式呈现。我有一个脚本,它将收集对象或数组中的信息,数组的每个元素都是一个对象。每个植物都有一个 3 位数的 id,用作对象和数组中的键,如下所示: 对象[143].create_date = 2012 年 12 月 15 日 数组[143].create_date = 12/15/2012

对象和数组都已正确创建。

问题:

var pRet = HtmlService.createTemplateFromFile('Plant Listing');

我无法使用 HtmlService 和 html 模板将数据导入 html。使用对象时的形式为

pRet.data = myObject;

html模板内代码如:

<? for(var x in data) { ?>
<? data[x].create_date ?>

呈现为 TypeError:无法从 null 读取属性“create_date”。但是如果我像这样将数据传递给模板:

pRet.Data = myObject[143];

然后渲染的 html 循环并显示 id 为 143 的植物的数据元素。如果我使用将植物作为植物 id 的数组索引返回的函数,那么我得到一个元素为 0 到 99 的数组未定义,具有任何数据的第一个元素是元素 100,对应于 id 为 100 的植物。

我将预读表中的数据呈现为对象的代码返回一个具有如下元素列表的对象:

{143={stage_7=-1.0, index=20.0, stage_5=-1.0, stage_6=-1.0, stage_3=1.0, current_stage=1.0, strain=1.0, stage_4=0.0, location=1.0, stage_1=51.0, stage_2=61.0, id=143.0, create_date=Sat Dec 08 2012 00:00:00 GMT-0700 (MST), group=null}

将数据集作为以植物 id 为索引的数组返回的代码会返回此值,其中前 100 个元素为空,因为第一个植物索引为 100:

{stage_7=-1.0, index=1.0, stage_5=-1.0, stage_6=-1.0, stage_3=5.0, current_stage=2.0, strain=1.0, stage_4=-1.0, location=2.0, stage_1=Mon Jul 09 23:00:00 PDT 2012, stage_2=56.0, id=100.0, create_date=Sat Dec 08 2012 00:00:00 GMT-0700 (MST), group=null}

问题: 我可以尝试将数据从电子表格获取到呈现的 html 的其他方法是什么?我最初的想法是放弃将元素放在植物 id 的数组或对象索引中的想法。另一种选择是使用数组并检查模板文件中的空条目。

【问题讨论】:

    标签: javascript object google-apps-script


    【解决方案1】:

    HtmlService 中有一个已知错误,您无法将子属性分配给模板上的对象。所以这失败了:

    var = HtmlService.createTemplate();
    t.x = {};
    t.x.y = 1;  // This throws no error, but t.x.y will still be undefined!
    

    但是这有效:

    var = HtmlService.createTemplate();
    var x = {};
    x.y = 1;
    t.x = x;    // t.x.y will now correctly be 1
    

    我们知道问题出在哪里,并计划解决它,但这并不重要,需要一些时间才能推出。

    【讨论】:

    • 这个问题解决了吗?我已经就将数据从服务器传递到客户端 html 做出了另一个全面的答案:stackoverflow.com/a/38314034/2213940
    • 是的,这是固定的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    相关资源
    最近更新 更多