如何使用盖茨比显示图像和Markdown文件的文件夹 [英] How to use Gatsby to display a folder of images and markdown files

查看:60
本文介绍了如何使用盖茨比显示图像和Markdown文件的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我对Gatsby,react,GraphQL等并不陌生.过去,我使用纯CSS,HTML和javascript制作网站.虽然,我对盖茨比及其功能很感兴趣,所以我决定挑战自我并学习它.

我正在为自己准备一个投资组合站点,并且为了便于更新,我希望能够通过创建新文件夹,运行构建脚本并将构建的站点拖放到我的FTP中来添加新项目.

这是我设置项目文件夹结构的方式:

  -src-项目--- 1-大堂森山---- 1-dm-frontcover.jpg---- 2-dm-spread.jpg---- 3-dm-backcover.jpg----project-metadata.md[...]--- 2-午餐包---- 1-lf-wordmark.png---- 2-lf-logo.png---- 3-lf-poster.jpg----project-metadata.md[...] 

该站点是单个页面,因此无需为每个项目创建新页面.我只是将它们分类到编号的文件夹中,因为这对于我自己来说是最容易更新的.

理想情况下,我想从每个项目的markdown文件中获取标题和说明,并将标题放在h3中,将说明放在ap中,然后在div中显示图像,样式化后将变成旋转木马./p>

设计样机

我当前的进度

我一直在运行一些测试,并且能够使用allMarkdownRemark访问markdown文件,并使用allImageSharp访问图像.它虽然很hacky,但确实有效,唯一的问题是它显示的是图像的 all ,而不仅仅是显示每个项目所需的图像.假设我在一个项目中有8张图像,在另一个项目中有5张图像,它将显示所有13张图像.

有没有办法做我想与盖茨比做的事情?还是我应该放弃并回到杰基尔…

gatsby-config.js:

  module.exports = {siteMetadata:{标题:"J.C.R."},插件:['gatsby-plugin-react-helmet','gatsby-plugin-sass',{解决:"gatsby-source-filesystem",选项: {名称:项目",路径:`$ {__ dirname}/src/projects/`}},'gatsby-transformer-remark','gatsby-transformer-sharp',"gatsby-plugin-sharp",`@ dream-bit-de/gatsby-plugin-better-page-tree`]} 

gatsby-node.js:

  const path = require('path')module.exports.onCreateNode =({节点,操作})=>{const {createNodeField} =操作如果(node.internal.type ==='MarkdownRemark'){const slug = path.basename(path.dirname(node.fileAbsolutePath,'.md'))createNodeField({节点,名称:'slug',值:ug})}} 

工作组件:

  import从'react'进行React从"gatsby"导入{graphql,useStaticQuery}从"gatsby-image"导入图像const Work =()=>{const data = useStaticQuery(graphql`询问 {allMarkdownRemark(排序:{顺序:ASC,字段:[frontmatter ___ position]}){边缘{节点{前题{标题描述}字段{sl}}}}allFile(筛选: {ext:{eq:".jpg""}},种类: {订单:ASC,栏位:[relativePath]}){边缘{节点{relativePathrelativeDirectory名称分机ID根据}}}}`)console.log(数据)返回 (< div id =工作">< ol>{data.allMarkdownRemark.edges.map((edge)=> {返回 (< li class = {edge.node.fields.slug}>< h3> {edge.node.frontmatter.title}</h3>< p> {edge.node.frontmatter.description}</p>{data.allFile.edges.map((edge)=> {返回 (< img src = {`../projects $ {edge.node.relativeDirectory}/$ {edge.node.name}-$ {edge.node.base} $ {edge.node.ext}`}><<;/img>)})}</li>)})}</ol></div>)}导出默认工作 

index.js:

  import从'react'进行React从'../components/head'导入Head从"../components/info"导入信息从"../components/work"导入作品导入'../styles/index.scss'const indexPage =()=>{返回 (< div>< Head/>< Info/><工作/></div>)}导出默认indexPage 

解决方案

这比您到目前为止尝试的要容易得多.我建议使用 gatsby-image ,因为添加以下内容后,图像将属于Gatsby生态系统:

  {解决:"gatsby-source-filesystem",选项: {名称:项目",路径:`$ {__ dirname}/src/projects/`}}, 

Gatsby将在内部解析/src/projects/中的所有内容,并将创建节点以使该模式可用于GraphQL,因此:

  {allFile(过滤器:{扩展名:{eq:"jpg""}}){边缘{节点{childImageSharp {体液{...盖茨比ImageSharpFluid}}}}}} 

然后在您的组件中:

  {data.allFile.edges.map((edge)=> {return< Img fluid = {edge.childImageSharp.fluid}/>})} 

So I'm very new to Gatsby, react, GraphQL, etc. In the past I've used pure CSS, HTML, and javascript to make my sites. Although, I was interested in Gatsby and the capabilities of it, so I decided to challenge myself and learn it.

I'm putting together a portfolio site for myself and for ease of updating, I would like to be able to add new projects through creating new folders, running a build script, and dropping the built site into my FTP.

This is how my folder structure for projects is set up:

-src
--projects
---1-daido-moriyama
----1-dm-frontcover.jpg
----2-dm-spread.jpg
----3-dm-backcover.jpg
----project-metadata.md
[...]
---2-lunch-from-a-care-package
----1-lf-wordmark.png
----2-lf-logo.png
----3-lf-poster.jpg
----project-metadata.md
[...]

The site is a single page, so no need to create new pages for each project. I just have them sorted into numbered folders because that would be the easiest to update for myself.

Ideally I would want to take the title and description from each project's markdown file, and put the title in an h3, the description in a p, and then display the images in a div, which when styled will become a carousel.

Mockup of the design

My current progress

I've been running some tests and have been able to access the markdown files using allMarkdownRemark, and the images using allImageSharp. It was hacky, but it worked, the only problem is that it was displaying all of the images, and not just the images needed for each project. Say, I have 8 images in a project, and 5 in another, it would display all 13 images.

Is there a way to do what I'm trying to do with Gatsby? Or should I just give up and move back to Jekyll…

gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: 'J.C.R.'
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-sass',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'projects',
        path: `${__dirname}/src/projects/`
      }
    },
    'gatsby-transformer-remark',
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    `@dream-bit-de/gatsby-plugin-better-page-tree`
  ]
}

gatsby-node.js:

const path = require('path')

module.exports.onCreateNode = ({ node, actions}) => {
    const {createNodeField} = actions

    if (node.internal.type === 'MarkdownRemark') {
        const slug = path.basename(path.dirname(node.fileAbsolutePath, '.md'))
        createNodeField({
            node,
            name: 'slug',
            value: slug
        })
    }
}

Work component:

import React from 'react'
import { graphql, useStaticQuery } from 'gatsby'
import Img from 'gatsby-image'

const Work = () => {
    const data = useStaticQuery(graphql`
        query {
            allMarkdownRemark(
                sort: { order: ASC, fields: [frontmatter___position]}
            ) {
            edges {
                node {
                    frontmatter {
                        title
                        description
                    }
                    fields {
                        slug
                    }
                }
            }
            }
            allFile (
            filter: { 
                ext: {eq: ".jpg"}
            },
            sort: { 
                order: ASC, 
                fields: [relativePath]
            }
            ) {
                edges {
                node {
                    relativePath
                    relativeDirectory
                    name
                    ext
                    id
                    base
                }
            }
            }
        }
    `)

    console.log(data)
    return (
        <div id="work">
            <ol>
                {data.allMarkdownRemark.edges.map((edge) => {
                    return (
                        <li class={edge.node.fields.slug}>
                            <h3>{edge.node.frontmatter.title}</h3>
                            <p>{edge.node.frontmatter.description}</p>
                            {data.allFile.edges.map((edge) => {
                                return (
                                    <img src={`../projects${edge.node.relativeDirectory}/${edge.node.name}-${edge.node.base}${edge.node.ext}`}></img>
                                )
                            })}
                        </li>
                    )
                })}
            </ol>
        </div>
    )
}

export default Work

index.js:

import React from 'react'
import Head from '../components/head'
import Info from '../components/info'
import Work from '../components/work'
import '../styles/index.scss'

const indexPage = () => {
  return (
    <div>
      <Head/>
      <Info/>
      <Work/>
    </div>
  )
}

export default indexPage

解决方案

It's much easier than you've tried so far. I would recommend using gatsby-image since all the images belong to the Gatsby ecosystem when you add the following:

{
  resolve: 'gatsby-source-filesystem',
  options: {
    name: 'projects',
    path: `${__dirname}/src/projects/`
  }
},

Gatsby internally will parse everything inside /src/projects/ and will create nodes to make the schema available for GraphQL, so:

{
  allFile(filter: {extension: {eq: "jpg"}}) {
    edges {
      node {
        childImageSharp{
          fluid{
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}

Then in your component just:

{data.allFile.edges.map((edge) => {
   return <Img fluid={edge.childImageSharp.fluid} />
})}

这篇关于如何使用盖茨比显示图像和Markdown文件的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆