1
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 3 years have passed since last update.

Gatsby ブログやコンテンツ一覧で抜粋と続きを読むリンクの表示をする方法

Posted at

Gatsbyでブログの一覧ページを作るときにタイトルと抜粋、続きを読むリンクを表示したいときのやり方。

ドキュメントはこちら
https://www.gatsbyjs.org/packages/gatsby-transformer-remark/

プラグインをインストール

npm install --save gatsby-transformer-remark

コンフィグ設定

// In your gatsby-config.js
plugins: [
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      excerpt_separator: `<!-- end -->`,
    },
  },
],

grphqlでデータ取得

抜粋をHTMLで返す場合にはformatの設定が必要。テキストでいいならexcerptのみでOK。

{
  allMarkdownRemark {
    edges {
      node {
        excerpt(format: HTML)
      }
    }
  }
}

コンポーネントでデータ表示

const ExcerptComponent = (props) => {
  const post = props.data.node.frontmatter
  const content = props.data.node
  return (
    <h2 className="title">{post.title}</a></h2>
    <p className="excerpt" dangerouslySetInnerHTML={{ __html: content.excerpt }}/>
    <a href={post.slug}>続きを読む</a>
  )
}

markdownにタグを入れる

---
title: コンテンツのタイトル
description: コンテンツの説明文
date: 2020-04-02T11:30:00+09:00
slug: "excerpt-test"
---

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Corrupti, accusantium, ut ducimus voluptate perferendis sequi asperiores iusto.

<!-- end -->

ここから下は抜粋に表示されない

Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde vel labore quia quas molestiae doloremque nisi saepe illo optio. Rem repudiandae est ipsum eius cum ipsam iusto odio vel labore?
1
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
1
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?