1
votes

I am trying to use an array as the datasource using HtmlService and the Datatables plugin for jquery. I am having trouble passing an array. The resulting table is not rendering the array correcty - in this 3 col table, col1 contains '1', col2 contains ',' col3 contains '2' What am I doing wrong?

function doGet() { 
var temp = HtmlService.createTemplateFromFile('example2');
temp.j = [1,2,3];            
return temp.evaluate();  
}

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <title>DataTables example</title>

    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.1/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.1/jquery.dataTables.min.js"></script>
    <script type="text/javascript" charset="utf8">
        $(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
    "aaData": [
        /* Reduced data set */
         <?= j ?> 

    ],
    "aoColumns": [
        { "sTitle": "Engine" },
        { "sTitle": "Browser" },
        { "sTitle": "Platform" }
    ]
} );   
} );
  </script>
</head>
<body>
<div id="demo"></div>

</body>
</html>
1

1 Answers

2
votes

A couple of ideas. Let me know which you prefer/works best. You can write your [1,2,3] as a string and throw that at your template. Like this:

temp.j = Utilities.jsonStringify([1,2,3]);

<?!= j ?>

Note: the ! is necessary here because it forces the string to be printed as is. See 'Force-Printing Scriptlets'.

Or you can iterate through each element of your data in the html template like this.

[<? for  (var i = 0; i < j.length; ++i) { ?>
  <?!= j[i]?>,
<? } ?>]

Note: the square brackets and commas are necessary because j[i] just returns the value of each element.