302 文字
2 分
外部にあるmarkdownファイルをAstroのContent collectionsに追加する
Astro 5.12.3 で、GitHub プロフィールをそのまま About ページに表示したくなった。 そこで他のリポジトリで公開している README.md を取得する loader を作成した。
次の記述で GitHub の README.md を Content collections に追加することが出来る。
const spec = defineCollection({ loader: { name: "my-github-readmer", load: async ({ renderMarkdown, store }) => { const response = await fetch( "https://raw.githubusercontent.com/hrdtbs/hrdtbs/refs/heads/master/README.md" ); const entry = await response.text();
store.clear(); store.set({ id: "about", data: { entry, }, rendered: await renderMarkdown(entry), }); }, },});
export const collections = { // Other collections ... spec,};
defineCollection
のloader
には、元々用意されているfile
やglob
を利用する方法Builit-in loaders
だけでなく、自分でファイルを取得する関数を指定する方法Inline loaders
や、今回利用したオブジェクトを指定する方法Object loaders
がある。
恐らくInline loaders
でも同様の記述が出来ると思うが、Object loaders
の場合は引数からrenderMarkdown
を取得することが出来るため、markdown ファイルを取得するようなケースでは手軽だと思われる。
Content collections に追加されるため、次のように利用できる。
---import { getEntry, render } from "astro:content";
const aboutPost = await getEntry("spec", "about");const { Content } = await render(aboutPost);---<Content />
外部にあるmarkdownファイルをAstroのContent collectionsに追加する
https://blog.ohirunewani.com/posts/astro-external-markdown-loading/