hy clear Blog

【microCMS】Steam Widgetを表示させたい

2024/07/19

2024/08/23

📰 アフィリエイト広告を利用しています

はじめに

このブログはmicroCMSとNext.jsを使ってSSGで出力後、ホスティングしています。

microCMSの埋め込み機能でSteamWidgetのURLのみを指定して埋め込むと以下のように表示される

値段などを含めた以下のようなよく見る表示ができるようにしたかったのでメモ

最善の方法かはわからない。もっといい方法があれば教えてほしい

手順

SSGでの方法です。

以下のコードを表示したい。特定の文字を記事に含め、それをNext.js側で置換している。

omegacrafter
<iframe src="https://store.steampowered.com/widget/2262080/" className=" border-0" width="646" height="190"></iframe>

microCMS側

  1. 「段落(pタグ)」でルールに基づいたテキストを入力する。
    今回は「replaceSteamWidget_<ゲーム名>_iframe」とし、前後の文字列で変換が必要かチェックしている

Next.js側

ウィジェットのリストを作成する

steamWidgets.ts
// ゲーム名がkeyになる辞書を作成
export const steamWidgets: Record<string, string> = {
    Gatekeeper: `<iframe src="https://store.steampowered.com/widget/2106670/" className=" border-0" width="646" height="190"></iframe>`,
    IslandsOfInsight: `<iframe src="https://store.steampowered.com/widget/2071500/740103/" className=" border-0" width="646" height="190"></iframe>`,
    OmegaCrafter: `<iframe src="https://store.steampowered.com/widget/2262080/" className=" border-0" width="646" height="190"></iframe>`
}

pタグをすべて検査し、ルールに合う場合に変換する

読み込んだコンテンツからpタグをすべて検査し、前後の文字が設定したルールに合う場合にiframeに変換する。
処理はcheerioを使用している

app.tsx
import { load } from "cheerio";

//...

    const $ = load(post.content, null, false)
    // iframeを挿入
    $("p").each(function () {
        const element = $(this)
        if (element.children().length !== 0) return;
        const text = element.text()
        if (!text.startsWith("replaceSteamWidget")) return;
        if (!text.endsWith("iframe")) return;
        // テキストを設定してから追加する
        element.text("")
        element.append(steamWidgets[text.split("_")[1]])
    })

  var result = $.html()

最後に

目的は達成できたが、あんまりすっきりしない方法になってしまった。
以下の方法でできないか調べる