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

gatsby_如何使用Gatsby.js来获取内容相关推荐

  1. gatsby_如何在Gatsby.js中使用本地状态保持页面之间的状态

    gatsby Cover Photo by Anas Alshanti on Unsplash 封面图片由Anas Alshanti拍摄于Unsplash 问题" (The "pr ...

  2. JS中编写函数去除HTML标签,js函数获取html中className所在的内容并去除标签

    js函数获取html中className所在的内容并去除标签 复制代码 代码如下: function queryClass(classnames){ var classobj= new Array() ...

  3. php 修改input内容,JS简单获取并修改input文本框内容的方法示例

    这篇文章主要介绍了JS简单获取并修改input文本框内容的方法,结合实例形式分析了JavaScript针对页面元素的获取.赋值等相关操作技巧,需要的朋友可以参考下 本文实例讲述了JS简单获取并修改in ...

  4. Jsoup获取动态js生成的内容

    Jsoup本身是只能获取到静态页面的数据,并无法获取动态生成的内容,所以单单使用jsoup是无法获取到js生成的内容的.我这里使用了htmlunit来获取网页内容后,将网页转换成xml格式,再通过js ...

  5. js怎么获取ueditor值_UEditor获取内容

    1,引入百度ueditor编辑器js库 以上两个js文件,请读者前往百度开放平台ueditor频道下载. 2, 之间添加html代码,其中获取内容等功能按钮也一并添加 获得整个html的内容 获得内容 ...

  6. JS编辑器获取选择内容的HTML多浏览器兼容性写法(支持Chorme、Firefox)

    昨天突然兴起,准备完善秋色园后台的编辑器关于Chrome.FireFox下的选择内容的HTML兼容处理. JS编辑器获取选择内容的HTML兼容性写法问题描述: 对于如何获取选择的文本(包括Html标签 ...

  7. html5在线显示word文档,JS实现获取word文档内容并输出显示到html页面示例

    本文实例讲述了js实现获取word文档内容并输出显示到html页面.分享给大家供大家参考,具体如下: title var w = new activexobject('word.application ...

  8. JS实现获取word文档内容并输出显示到html页面示例,和将页面数据写入txt文件

    JS实现获取word文档内容并输出显示到html页面示例 注意:这里使用了ActiveXObject组建,因此需要使用IE内核浏览器运行本代码. <!DOCTYPE html> <h ...

  9. html遍历table tr,js中获取 table节点各tr及td的内容简单实例

    js中获取 table节点各tr及td的内容简单实例 2019-01-06 编程之家 https://www.jb51.cc 编程之家收集整理的这篇文章主要介绍了js中获取 table节点各tr及td ...

最新文章

  1. Javascript 限制文本字节数
  2. target和currentTarget
  3. pywt.upcoef中take使用详解
  4. 使用CreateProcess和wcscat_s容易出错的地方
  5. 【浏览器】event.pageX/Y页面坐标(CSS像素) event.clientX/Y视口Viewport坐标(CSS像素) event.screenX/Y屏幕坐标(屏幕像素)
  6. 音频光端机的几个重要指标
  7. 蓝桥杯基础模块9:IO口扩展与存储器映射
  8. 内核热补丁,真的安全么?
  9. python转cpp_python转c工具
  10. 信息学奥赛C++语言:石头剪子布
  11. PHP心脏装置,“人工心脏”不再科幻 “钢铁侠”已成现实
  12. python随机生成两个一维数组_如何用python随机产生一个一维数组
  13. java设计模式工厂模式_Java中的外观设计模式
  14. Redis 学习之事务处理
  15. 关于websql语法
  16. 用matlab绘制圆锥曲线,如何用几何画板绘制圆锥曲线?
  17. 如何绕过mac地址过滤_Maccms V8 后台Getshell #2(绕过过滤)
  18. mogo语句常用用法
  19. opencv毛孔识别(python实现)
  20. Android自定义控件:NestedScrolling实现仿魅族flyme6应用市场应用详情弹出式layout

热门文章

  1. IOS 自定义相机, 使用 AVFoundation(附实现部分腾讯水印相机功能 demo)
  2. ECS 实例网络带宽
  3. lvs后端realserver的vip管理脚本lvs-realsvr.sh
  4. nginx 启动脚本
  5. 推荐两款简单好用的图片放大jquery插件
  6. 最多显示6行并且最多显示三条文本
  7. Android如何使用读写cookie的方法
  8. 1月国内操作系统市场:Windows XP份额高达60.84%
  9. iOS UITextField输入框随键盘弹出界面上移
  10. 高德地图关键字搜索oc版