この節では、microCMSから取得した複数の記事を、Google Apps ScriptのHTMLテンプレートへ渡し、一覧ページとして表示します。
一覧ページでは、タイトル、概要、公開日、サムネイル画像をカード形式で並べます。
GASのWebアプリへアクセスすると、最初にdoGet(event)が実行されます。
function doGet(event) {
const articleId = String(
event?.parameter?.id ?? '',
).trim();
if (articleId) {
return renderDetailPage(articleId);
}
return renderIndexPage();
}
URLにidパラメータがあるかどうかで、表示するページを切り替えています。
idなし
→ 記事一覧ページ
idあり
→ 記事詳細ページ
一覧ページのURLは次の形式です。
<https://script.google.com/macros/s/デプロイID/exec>
記事詳細ページは、URLに記事IDを追加します。
<https://script.google.com/macros/s/デプロイID/exec?id=記事ID>
記事一覧ページは、renderIndexPage()で生成します。
function renderIndexPage() {
const template =
HtmlService.createTemplateFromFile('index');
template.articles = getArticles();
return template
.evaluate()
.setTitle('ポートフォリオ')
.addMetaTag(
'viewport',
'width=device-width, initial-scale=1',
);
}
この関数では、次の処理を行っています。
index.htmlをテンプレートとして読み込む