bibby
bibby

Reputation: 21

How do I link Apps Script for loop to html?

Still new to Google Apps Script and I'm struggling connecting my Apps Script to my html file. As you can see in my Apps Script code below I've created a loop within Apps Script and for each iteration of the for loop I'd like to create a new heading in the html script, hence the "<?= question =>" scriplet linking to the Apps Script. Can anyone help me here?

Apps Script:

const name = "Name"

//This is calling the html template
function doGet() {
  
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var range_in_q = ws.getRange("A1:E" +  ws.getLastRow()).getValues();
  typeof(Logger.log(range_in_q));
  Logger.log(range_in_q.length);
  for (i = 0; i<range_in_q.length - 1; i++) {
      var questions = range_in_q[i + 1][0];
      var answers = range_in_q[i + 1][1];
      Logger.log(questions);
      Logger.log(answers);
  return HtmlService.createTemplateFromFile('index').evaluate();

  
  
  }
}


function includeExternalFile(filename) {
  return HtmlService.createTemplateFromFile(filename).getContent();
}

Html Code:

<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1><?= name ?></h1>
    <? for (let i=0; i<test; i++){ ?>
    <h1> <?= questions ?></h1>
    <? } ?>
    <h1>This page was served through HtmlService!</h1>

  </body>
</html>  
    

Upvotes: 0

Views: 838

Answers (1)

Tanaike
Tanaike

Reputation: 201358

Modification points:

  • In your script, when return HtmlService.createTemplateFromFile('index').evaluate(); is run in the loop, the function is finished.
  • name, questions and answers are not used in HtmlService.createTemplateFromFile('index').evaluate().
  • When the loop process is used in the HTML template, the process cost becomes high. Ref (Author: myself)

When these points are reflected in your script, how about the following modification?

Google Apps Script side:

const name = "Name"

function doGet() {
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var range_in_q = ws.getRange("A1:E" +  ws.getLastRow()).getValues();
  
  // I modified the below script.
  var questions = range_in_q.map(([a]) => `<h1>${a}</h1>`).join("");
  var html = HtmlService.createTemplateFromFile('index');
  html.name = name;
  html.questions = questions;
  return html.evaluate();
}

HTML side:

<html>

<head>
  <base target="_top">
</head>

<body>
  <h1><?= name ?></h1>
  <?!= questions ?>
  <h1>This page was served through HtmlService!</h1>
</body>

</html>
  • From your showing script, in this modification, answers is not used. Because I cannot know your expected situation using answers. Please be careful about this.

Note:

References:

Upvotes: 1

Related Questions