0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google Spreadsheetでランダムに出力するオミクジ的なサイトを作る(2)createTemplate編

Posted at

Google Spreadsheetでランダムに出力するオミクジ的なサイトを作る(1)
では、Google AppScriptのHtmlService.createHtmlOutput()を試したが、HTMLをハードコーディングするのも気持ち悪いので、HtmlService.createTemplateFromFile()を使ってみる。

まず、テンプレを作る。

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <? var data = getData(); ?>
    <h1><a href="<?= data[0] ?>" target="_top"><?= data[1] ?></a></h1>
  </body>
</html>

そして、今までdoGet()の中に詰め込んでたものを分割して、doGet()はcreateTemplateFromFileだけにして、データ生成はgetDataの中で行う。

function doGet() {
  return HtmlService
      .createTemplateFromFile('index')
      .evaluate();
}

function getData(){
  var spreadsheet = SpreadsheetApp.openById('シートID');
  var sheet = spreadsheet.getSheetByName('list');
  var lastRow = sheet.getLastRow();
  var rand = Math.floor( Math.random() * lastRow ) + 1;
  var url = sheet.getRange(rand,1).getValue();
  var title = URLtoTitle(url);
  return [url,title];
}

function URLtoTitle(url) {
  var response = UrlFetchApp.fetch(url);
  var myRegexp = /<title>([\s\S]*?)<\/title>/i;
  var match = myRegexp.exec(response.getContentText());
  var title = match[1];
  title = title.replace(/(^\s+)|(\s+$)/g, "");
  return(title);
}

一瞬、「このアプリケーションは、Google ではなく、別のユーザーによって作成されたものです。」という表示を消せるかな?と期待したが、結局、iframe構造は変わらないのでタイトルを設定しても反映できないがJavaScriptぐらいは使えるようになった。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?