当前位置: 首页 > 编程日记 > 正文

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

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

相关文章:

使用 AFNetworking 进行 XML 和 JSON 数据请求

(1)XML 数据请求 使用 AFNetworking 中的 AFHTTPRequestOperation 和 AFXMLParserResponseSerializer,另外结合第三方框架 XMLDictionary 进行数据转换 使用 XMLDictionary 的好处:有效避免自行实现 NSXMLParserDelegate 委托代理…

批处理+定时任务实现定时休息提醒

前言:俗话说的好,懒是第一生产力,懒是提高生产效率的必要条件。而现今windows是大部分人的第一生产工具,批处理定时任务这对黄金搭档就是提升生产效率的第一工具。大家在生产过程中经常会遇到各种周期性的重复的工作,比…

后端返回的数据中换行符 html换行

标签代码 <span v-html"model3_txt"></span> vue js代码 var txt "恭喜你\n获得某某某奖品"; if(txt.indexOf(\n)!-1){var reg new RegExp("/r/n", "g");txttxt.replace(reg, "<br/>");console.log(t…

vim block vim_如何不再害怕Vim

vim block vim精选最流行的命令以及如何使用它们 (A curation of the most popular commands and how to use them) If you’ve ever used Vim, you know how difficult it can get to reach the same speed as in a “normal” GUI editor. But once you do, the payoff is ex…

android EditText 限定中文个数与英文个数的解决方式

EditText 限定中文8个英文16个的解决方法。 在EditText上控件提供的属性中有限定最大最小长度的方法。可是&#xff0c;对于输入时&#xff0c;限定中文8个英文16个时&#xff0c;怎么办&#xff1f;相当于一个中文的长度是两个英文的长度。原理就不说了。自己看一下android的源…

根据二叉树的前序遍历和中序遍历重建二叉树

题目描述 输入某二叉树的前序遍历和中序遍历的结果&#xff0c;请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}&#xff0c;则重建二叉树并返回。1 /**2 * Definition for …

VUE 监听当前路由 侦听器 watch

侦听器&#xff1a; 你可以利用侦听器&#xff0c;响应数据的变化&#xff0c;例如路由&#xff0c;和页面中data的值&#xff0c;可以在他们变化的时候写相应的处理逻辑在侦听器中。 侦听器的使用很简单&#xff1a; watch 对象就是侦听器&#xff0c;只有当侦听的值改变了它…

如何使用Bootstrap4和ES6创建自定义确认框

by Prashant Yadav通过Prashant Yadav 如何使用Bootstrap4和ES6创建自定义确认框 (How to create a custom confirm box with Bootstrap4 and ES6) We put lots of sweat into achieving a good design, but imagine a scenario where we have to use something which is styl…

RequireJS学习笔记(转)

前言进入移动前端是很不错的选择&#xff0c;这块也是我希望的道路&#xff0c;但是不熟悉啊。。。现在项目用的是requirebackbone&#xff0c;整个框架被封装了一次&#xff0c;今天看了代码搞不清楚&#xff0c;觉得应该先从源头抓起&#xff0c;所以再看看require了。上午是…

火狐中的table

在火狐浏览器中&#xff0c;table的th、td会存在小数转载于:https://www.cnblogs.com/likwin/p/7270817.html

React路由 react-router-dom

React的路由&#xff1a; 首先我们创建一个React应用 npm install -g create-react-app create-react-app demo-app cd demo-app安装路由 npm install react-router-dom npm add babel/runtime 接下来&#xff0c;将以下任一示例复制/粘贴到中src/App.js。 第一个示例&…

编程基础 垃圾回收_为什么我回收编程问题

编程基础 垃圾回收by Amy M Haddad通过艾米M哈达德(Amy M Haddad) 为什么我回收编程问题 (Why I Recycle Programming Problems) Many programmers are given the same advice: solve as many problems as possible. It’s true that solving new problems can help you gain …

SQL Server孤立账户解决办法

选择你想要的数据库。 执行 exec sp_change_users_login UPDATE_ONE,用户名,登录名 假如你的登录名是&#xff1a;sd exec sp_change_users_login UPDATE_ONE,sd,sd 转载于:https://www.cnblogs.com/runliuv/p/7273675.html

vue更新data无效,页面data没刷新 vue.set

Vue中组件的data是有很多坑的&#xff0c;先普及一下常识&#xff1a; 1.想使用data&#xff0c;必须先在data中创建。&#xff08;如果不创建就会报错&#xff09;示例&#xff1a; <div class"">{{user.Age}}</div>new Vue({el: #app,data: {user:{A…

重温Thinking in java

1、高精度 BigInteger、BigDecimal 支持任意大小的数字 不能使用运算符 运算速度相对于int、float稍慢 2、对象作用域 {String s new String("aaa"); } 在}外 此时栈中的引用s已经超出了自己的作用域 便不存在了 但是new String("aaa")这个堆中的对象仍然…

2018 react 大会_React Conf 2018的经验教训

2018 react 大会by Yangshun Tay阳顺泰 React Conf 2018的经验教训 (Lessons Learned at React Conf 2018) I was fortunate to have attended React Conf 2018 thanks to my managers — it was an awesome event. I have been watching past React Conf videos online and i…

删除url中某个参数

这里的url 是指一个网站链接 例如&#xff1a; https://baidu.com?a1&b2 下面看一下封装的代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><script src"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js&q…

【转载】MSXML应用总结 开发篇(下)

原文&#xff1a;http://blog.sina.com.cn/s/blog_48f93b530100eq4b.html 三、查询XML文档节点 这部分属于“读”XML文档并做节点遍历&#xff0c;由于担心加上实例会占用过多的篇幅影响阅读&#xff0c;先在这篇做方法总结&#xff0c;以后有时间再写一篇“实战篇”专门写个实…

d010:盈数、亏数和完全数

题目: 对一个正整数N而言&#xff0c;将它除了本身以外所有的因子加起来的总和为S&#xff0c;如果S>N&#xff0c;则N为盈数&#xff0c;如果S<N&#xff0c;则N为亏数&#xff0c;而如果SN&#xff0c;则N为完全数&#xff08;Perfect Number&#xff09;。例如10的因子…

软件开发 理想_我如何在12个月内找到理想的软件工作

软件开发 理想In this talk, Matt Woods shares the 3 cornerstone habits that helped him land his dream software job in just 12 months. These habits paved the way for him to consistently grow as a software developer, balloon his professional network, and easi…

Angular4.0从入门到实战打造在线竞拍网站学习笔记之四--数据绑定管道

Angular4.0基础知识之组件Angular4.0基础知识之路由Angular4.0依赖注入Angular4.0数据绑定&管道 数据绑定 数据绑定允许你将组件控制器的属性和方法与组件的模板连接起来&#xff0c;大大降低了开发时的编码量。 常见的表现形式有&#xff1a; 插值表达式&#xff1a;<h…

给GridView增加求和行

1、在WebForm窗体中&#xff0c;设置GridView的ShowFooter"True" 2、在后台代码中 private int jhrs0,ybrs0;//定义变量 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > 0) { jhrs Convert.ToInt16(e.Ro…

phpMyAdmin 数据库添加int类型的值时默认设为唯一主键的问题解决

数据库的表中插入了一条数据&#xff0c;再插入数据就插入不进去。 这是我今天在开发数据库的时候&#xff0c;遇到一个问题&#xff0c;经过排查&#xff0c;是数据库的结构有问题&#xff0c;有字段是唯一数据&#xff0c;但是目前还不想设置它的值。 场景环境描述&#xff…

python 类中定义类_Python中的动态类定义

python 类中定义类Here’s a neat Python trick you might just find useful one day. Let’s look at how you can dynamically define classes, and create instances of them as required.这是一个整洁的Python技巧&#xff0c;有一天可能会有用。 让我们看一下如何动态定义…

用自定义方法,传入成绩数组,实现输出考试成绩的成三名

package com.imooc; import java.util.Arrays; //导入Array类包 import java.util.Scanner; //导入Scanner类包 public class Final2 { public static void main(String args[]){Scanner…

EJS 什么是EJS后缀文件 EJS怎么用

一、什么是EJS EJS是一个JavaScript模板库&#xff0c;用来从JSON数据中生成HTML字符串。 二、为什么要使用EJS 与最初的JavaScript相比较&#xff0c;一些不太了解你的代码的人可以更容易地通过EJS模板代码看得懂你的代码。 让我们放松一下&#xff0c;一起来享受下令人激动的…

一个推荐系统,实现完整的设计-在百度搜索关键词推荐案例

在之前一篇博文中&#xff0c; 有同学在评论中问了个问题&#xff1a; 怎样解决因式分解带来的推荐冷门。热门关键词的问题。 在回答这个问题的时候&#xff0c; 想到了近几年在做搜索推荐系统的过程中&#xff0c; 学术界和工业界的一些差别。 正好近期正在做技术规划&#xf…

如何充分利用JavaScript(ES6)中的解构功能

by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) Destructuring was a new addition to ES6. It took inspiration from languages like Python and allows you to extract data from arrays and objects into distinct variables. It might sound like something you’ve done in…

React 开发环境搭建

先来一个 React 官方文档的链接 点击跳转 搭建 React 的前期准备&#xff1a;你的本地环境需要安装 cnpm、node。 注&#xff1a;代码块中的 $ 代表&#xff1a; $后面是在命令行输入的命令&#xff0c;举例 $ npm start 解&#xff1a;实际上是应该打开命令行输入 npm st…

c++中的友元重载

1 语法 返回值类型 operator 运算符名称(形参列表) { 重载实体 } --------->operator和运算符名称在一起构造成新的函数名 2 案例 1 #include <iostream>2 3 using namespace std;4 5 class Complex6 {7 public:8 9 Complex(float x0,float y0) 10 :_…