当前位置: 首页 > 工具软件 > Gatsby > 使用案例 >

gatsby_如何使用Gatsby.js来获取内容

阎冠玉
2023-12-01

gatsby

by Dimitri Ivashchuk

由Dimitri Ivashchuk

如何使用Gatsby.js来获取内容 (How to source content with Gatsby.js)

Gatsby.js is a powerful static site generator (with dynamic capabilities) which can be used to build super performant web-sites. It has a very rich plug-in functionality and is perfect for your next personal blog, product landing, portfolio page or small e-commerce app.

Gatsby.js是功能强大的静态网站生成器(具有动态功能),可用于构建性能卓越的网站。 它具有非常丰富的插件功能,非常适合您的下一个个人博客产品登陆产品组合页面小型电子商务应用程序

采购内容 (Sourcing content)

It’s fairly evident that when you build your web-site, apart from business logic, performance, security and stylings, you care about actual content presented to an end user.

显然,在构建网站时,除了业务逻辑,性能,安全性和样式之外,您还关心呈现给最终用户的实际内容。

The case may be fairly simple: let’s say you have a product page with sections that need to be edited by marketing team which doesn’t want to edit those fancy h1’s and p’s in the code editor.

情况可能很简单:假设您有一个产品页面,其中的部分需要营销团队进行编辑,而这些部分不想在代码编辑器中编辑那些花哨的h1p

Another scenario may be personal-blog page which has lots of posts, with each post having its own title, content, and tons of other information that you might want to display.

另一种情况是个人博客页面,其中包含很多帖子,每个帖子都有自己的标题,内容以及大量您可能想显示的其他信息。

Thanks to loads of plugins written by community and Gatsby maintainers, we are lucky to choose from a wide range of options to get our content on the page.

感谢社区和Gatsby维护者编写的大量插件,我们很幸运地从众多选项中进行选择,以使我们的内容显示在页面上。

使用gatsby-source-filesystemgatsby-markdown-remark从项目文件夹进行采购 (Sourcing from project folder with gatsby-source-filesystem and gatsby-markdown-remark)

One of the easiest ways to grab our content is to source it directly from our project folder. We can grab assets like images, and more complicated content types like blog posts written in markdown.

获取内容的最简单方法之一是直接从项目文件夹中获取内容。 我们可以获取图像等资产,以及更复杂的内容类型,如以markdown编写的博客文章。

Scenario 1: Access images from assets folder to display them on the page
方案1:访问资产文件夹中的图像以在页面上显示它们

First we need to install gatsby-source-filesystem and set it up in gatsby-config.js.

首先,我们需要安装gatsby-source-filesystem并将其设置在gatsby-config.js

npm install gatsby-source-filesystem

npm install gatsby-source-filesystem

In gatsby-config.js:

gatsby-config.js

With the lines above we are telling Gatsby that we want to allow GraphQL to query all the insides of assets folder of our project located at the specified path.

在上面的几行中,我们告诉Gatsby,我们要允许GraphQL查询位于指定path项目assets所有内部文件。

Now that the plugin is prepared, we can actually query our assets folder with the following graphQL query ( sourceInstanceName is a filter parameter that corresponds to the name in the config above):

现在已经准备好了插件,我们实际上可以使用以下graphQL查询来查询我们的资产文件夹( sourceInstanceName是一个过滤器参数,与上面的配置中的name相对应):

Note that to be able to use images returned by this query inside component rather than inside of page, we need to use StaticQuery available from Gatsby.

需要注意的是要能使用内部由该查询返回的图像component ,而不是内部的page ,我们需要使用StaticQuery可以从Gatsby

StaticQuery accepts the query prop where we can use our GraphQL query from above and render prop which renders whatever we feed to it that has access to data which is nothing more than a wrapper for our queried files.

StaticQuery接受query道具,在这里我们可以从上方使用GraphQL查询并render道具,该道具渲染我们提供给它的任何可以访问data ,这些data只不过是查询文件的包装器。

If you are querying the same images but want to use them inside one of your pages you can access it directly from props.data

如果要查询相同的图像,但要在pages之一中使用它们,则可以直接从props.data访问它

Scenario 2: Access one particular image to display it on the page
方案2:访问一个特定的图像以将其显示在页面上

To access one particular image by its name, we have to adapt our GraphQL query a little bit. Otherwise we can use it in the ways described above in first scenario by using StaticQuery in component and props.data in page.

要通过名称访问一个特定的图像,我们必须对GraphQL查询进行一些调整。 否则,我们可以在第一种情况下通过使用组件中的props.data和页面中的StaticQuery以上述方式使用它。

Let’s specify the absolute path to the file and use a regex to cherry pick the desired image.

让我们指定文件的绝对路径,并使用正则表达式来挑选所需的图像。

Scenario 3: Access blog post written in markdown together with its frontmatter
方案3:访问以markdown撰写的博客文章及其前题

As Gatsby is often used as a blog template, it offers a very convenient way of working with blogposts written in markdown. To access markdown posts, we first need to tweak our config a little bit so that Gatsby knows where our markdown files live.

由于Gatsby通常用作博客模板,因此它提供了一种非常方便的方式来处理以markdown编写的博客文章。 要访问markdown帖子,我们首先需要对配置进行一些调整,以便Gatsby知道markdown文件位于何处。

We use gatsby-source-filesystem to achieve that:

我们使用gatsby-source-filesystem实现以下目的:

To be able to work with markdown files in a really convenient way, we also need to set up gatsby-transformer-remark plugin. Note how we add other plugins inside of gatsby-transformer-remark like gatsby-remark-images or gatsby-remark-prismjs. Those are here so we are able to directly embed images into our markdown and highlight code chunks with prismjs, respectively.

为了能够以一种非常方便的方式使用markdown文件,我们还需要设置gatsby-transformer-remark插件。 请注意,我们如何在gatsby-transformer-remark内部添加其他插件,例如gatsby-remark-imagesgatsby-remark-prismjs 。 这些都在这里,因此我们能够直接将图像嵌入到markdown并分别使用prismjs突出显示代码块。

With all of the above set up, we can now query our markdown posts with query (we can conveniently use sort to get our blog posts in chronological order and filter to be sure that we query only those markdowns which are located in the blog folder of our project):

随着上述所有集起来的,我们现在可以查询我们的降价职位与query (我们可以方便地使用sort让我们按照时间顺序和过滤博客文章,以确保我们的查询只有那些位于降价促销blog的文件夹我们的项目):

We already know that we can now access our markdown blog posts in any page just via this.props.data.allMarkdownRemark.edges, map trough them, and display all the necessary data generated for us by plugin.

我们已经知道,我们现在可以访问我们的markdown博客文章任何page只是通过this.props.data.allMarkdownRemark.edges ,地图槽他们,并显示通过插件为我们创建所有必要的数据。

For example, we have access to frontmatter which is nothing more than JSON-like structure that we include in our markdown.

例如,我们可以访问frontmatter ,它只不过是我们在markdown包含的类似于JSON的结构。

Here is a quick example:

这是一个简单的示例:

We have included title and date, but you can feel free to add any other parameters that you want to be accessible from the query (like tags in a form of array):

我们已经包括了标题和日期,但是您可以随意添加希望从查询中访问的任何其他参数(例如数组形式的标签):

无头CMS (Headless CMSs)

Sometimes its not really convenient to change all the content types like images or blog posts in the code editor. Moreover, your final user may not be aware of how to navigate through code and may require a more straightforward solution.

有时在代码编辑器中更改所有内容类型(如图像或博客文章)并不是很方便。 而且,您的最终用户可能不知道如何浏览代码,因此可能需要更直接的解决方案。

Scenario 4: Access complex content model from CMS and display the contents on the page
方案4:从CMS访问复杂的内容模型并在页面上显示内容

This is where headless CMS comes into play. Imagine a scenario where you make a static product page with Gatsby and pass it to the marketing department that is responsible for copywriting and images on the page. You built it with code — they interact with a user-friendly UI that makes it easy to change any content. Awesome!

这是无头CMS发挥作用的地方。 想象一个场景,您使用Gatsby制作了一个静态产品页面,并将其传递给负责该页面上的广告文案和图像的营销部门。 您是用代码构建的-它们与用户友好的UI交互,从而可以轻松更改任何内容。 太棒了!

Let’s explore how we would do it with Gatsby.js!

让我们探索如何使用Gatsby.js做到这一点!

从满足采购 (Sourcing from Contentful)

To be able to source something from Contentful you will need an account at https://www.contentful.com/. After registration you will get a simple example project that we will use for learning purposes.

为了能够从Contentful中获取某些东西,您需要一个https://www.contentful.com/上的帐户。 注册后,您将获得一个简单的示例项目,我们将用于学习目的。

For now let’s start with installing gatsby-source-contentful and adding it to our config.

现在,让我们开始安装gatsby-source-contentful并将其添加到我们的配置中。

npm install --save gatsby-source-contentful

npm install --save gatsby-source-contentful

In gatsby-config.js we need to add the plugin and provide our spaceId and accessToken which can both be found in the settings -> API keys of our project dashboard:

gatsby-config.js我们需要添加插件并提供我们的spaceIdaccessToken ,它们都可以在项目仪表板的settings-> API keys中找到:

Note that it’s not a good idea to expose your accessToken to the config file directly so it can be visible by everyone on GitHub. For training purposes, I will include it in the code for this tutorial, but try to use environment variables to protect your keys as it can be seen in the example above. If it's your first time seeing the term environment variable don't worry, you can grasp the concept from this post .

请注意,直接将您的accessToken公开给配置文件不是一个好主意,这样它可以被GitHub上的所有人看到。 出于培训目的,我将其包含在本教程的代码中,但尝试使用环境变量来保护您的密钥,如在上面的示例中可以看到的那样。 如果您是第一次看到environment variable一词不用担心,可以通过这篇文章了解这个概念。

Before we move any further, I want to show you how we can resolve a little conflict coming from the fact that some Contentful files are treated as markdown by Gatsby.

在继续进行之前,我想向您展示如何解决一些冲突,因为Gatsby将某些Contentful文件视为markdown

Our gatsby-node.js is responsible for programmatically creating pages from our markdown posts which are situated in the blog folder. By default it uses allMarkdownRemark query, which would source also Contentful markdown which we don't need. Let's adapt our query to source only those files which are located in our project folder:

我们的gatsby-node.js负责以编程方式从位于Blog文件夹中的markdown帖子创建页面。 默认情况下,它使用allMarkdownRemark查询,该查询还将获取我们不需要的Contentmark markdown。 让我们调整查询以仅获取位于项目文件夹中的那些文件:

In gatsby-node.js we have added filter and set it to /blog/:

gatsby-node.js我们添加了filter并将其设置为/blog/

Now we are ready to source our content from Contentful. In a new page named contentful.js we first want to query our assets that Contentful created for us. At the time, we have one particular interesting content type called Course which has all the necessary items for us to train.

现在,我们准备从Contentful中获取内容。 在一个名为contentful.js的新页面中,我们首先要查询Contentful为我们创建的资产。 当时,我们有一种特别有趣的内容类型,称为“ Course ,其中包含我们需要培训的所有必要项目。

It is straightforward to query Contentful assets with GraphQL, and all we need to do to get all the entries that are of type Course is to run the allContentfulCourse query.

使用GraphQL查询内容资产很简单,要获取所有类型为Course的条目,我们要做的就是运行allContentfulCourse查询。

You may have already guessed that we can query yourCustomType of content with allContentfulYourCustomType. Do note how we filter our courses on a language basis, otherwise we would get duplicates of every course in each language specified in Contentful. This is quite specific to this case, because every course has a translation:

您可能已经猜到,我们可以查询yourCustomType与内容allContentfulYourCustomType 。 请注意我们如何根据语言过滤课程,否则我们将获得Contentful中指定的每种语言的每门课程的副本。 这是针对这种情况的,因为每个课程都有翻译:

From exploring our content on Contentful, we can see that each Course has a title, duration, short description and image. We have included those in our query and now can access them in our component via this.props.data.

通过浏览内容丰富的内容,我们可以看到每个课程都有标题,持续时间,简短描述和图像。 我们已经在查询中包含了这些内容,现在可以通过this.props.data在我们的组件中访问它们。

回顾 (Recap)

In this small tutorial, you have learned several ways of sourcing different content types in Gatsby. You’ve also learned how to combine them in a single project, avoiding possible sourcing conflicts by precisely specifying what we want to query from what source.

在这个小教程中,您学习了几种在Gatsby中寻找不同内容类型的方法 您还学习了如何将它们组合到单个项目中,通过精确地指定我们要从哪个来源查询的内容来避免可能的采购冲突。

Thanks for reading! I hope you’ve enjoyed reading this post as much as I’ve enjoyed writing it! If you have any questions or want to bring up a discussion don’t hesitate to reach out to me on twitter. I would be happy if you hit that follow button so you don’t miss any future posts that I will release ?

谢谢阅读! 希望您喜欢阅读这篇文章,也喜欢阅读这篇文章! 如果您有任何疑问或想进行讨论,请随时在Twitter上与我联系。 如果您按下该“ follow按钮,我将很高兴,这样您就不会再错过我将来发布的任何帖子了吗?

As always you can find the code for this tutorial here on github

与往常一样,您可以在github上找到本教程的代码

Originally published at divdev.io

最初发布于divdev.io

翻译自: https://www.freecodecamp.org/news/how-to-source-content-with-gatsby-js-c220dde97e7/

gatsby

 类似资料: