AstroJavaScriptMarkdoc

Astro & Markdocで、独自のMarkdownタグを作成する

Markdocでは、{% custom %}Custom Tag{/% custom %}のような「独自のタグ」を作れます。 Astroでタグの作成・登録を行う方法を紹介します。 独自タグの描画内容を、実装する まずは「 […]

広告ここから
広告ここまで

Markdocでは、{% custom %}Custom Tag{/% custom %}のような「独自のタグ」を作れます。

Astroでタグの作成・登録を行う方法を紹介します。

独自タグの描画内容を、実装する

まずは「そのタグで何を描画するか」を実装しましょう。

例として、「常に別タブで開くリンクタグ」を作ります。

まずはsrc/components/markdoc/ExternalLink.astroに、以下のコードを追加します。

---

const { props } = Astro
---

<a {...props} target='_blank' rel='noopener noreferrer'>
    <slot></slot>
</a>

Astroにタグを登録する

独自タグが含まれることを、astro.config.mjsへ設定します。

import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';
import markdoc from "@astrojs/markdoc";
import tailwind from "@astrojs/tailwind";

import react from "@astrojs/react";

// https://astro.build/config
export default defineConfig({
  site: 'https://example.com',
  integrations: [mdx(), sitemap(), markdoc({
    tags: {
      externalLink: {
        render: 'ExternalLink',
        attributes: {
          class: {
            type: String,
          },
          href: {
            type: String,
          }
        }
      },
    }
  }), tailwind(), react()]
});

ページでMarkdocコンテンツと独自タグを読み込む

作成したコンポーネントを利用して、ページ内容を実装しましょう。

src/pages/tag-demo.astroを次のように実装します。

---
import { getEntryBySlug } from 'astro:content';
import ExternalLink from '../components/markdoc/ExternalLink.astro';

const entry = await getEntryBySlug('docs', 'tag-demo');

const { Content } = entry ? await entry.render() : { Content: null};
---

{Content ? (
    <Content
        components={{ ExternalLink }}
    />
): null}

コンテンツを作成する

あとはsrc/content/docs/tag-demo.mdocにタグを含む記事を書けばOKです。

{% externalLink
    class="text-underline text-indigo-600"
    href="https://stripe.com"
%}Stripe{% /externalLink %}

Referene

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts