所有Gatsby starter demos都有/gatsby-starter-blog/hi-folks/
如何使用/2015-05-28/hi-folks/
或仅/2015/hi-folks/
的年份进行设置。
谢谢!
答案 0 :(得分:3)
两个选项:
1)只需将博客帖子放在名为“你想要网址”的目录中,在这种情况下/2015-05-28/hi-folks/index.md
。
2)您可以通过从名为gatsby-node.js
的{{1}}导出函数来以编程方式设置路径。它为每个页面调用,包含页面来自的文件的文件系统数据+页面的元数据。所以说你想在markdown的frontmatter中设置帖子的日期,并且每个帖子都是一个简单的markdown文件,其路径如rewritePath
为了做你想做的事,你可以添加你的gatsby-node.js:
/a-great-blog-post.md
答案 1 :(得分:0)
rewritePath
。这是已确认可在Gatsby 2.3中使用的解决方案,
const m = moment(node.frontmatter.date)
const value = `${m.format('YYYY')}/${m.format('MM')}/${slug}`
createNodeField({ node, name: 'slug', value })
答案 2 :(得分:0)
在我的gatsby-node.js
文件中,添加了一个Slug生成器和一个模板解析器。
在src/posts
的内部,我在该文件夹中添加了一个文件夹2020
,创建的文件夹创建了类似my-blog-post
这样的条形地址路径,并且在这些文件夹中,我有一个index.md
文件
现在我有一个看起来像http://www.example.com/2020/my-blog-post/
的URL。
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/node-apis/
*/
const { createFilePath } = require(`gatsby-source-filesystem`);
// Generates pages for the blog posts
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`);
data.allMarkdownRemark.edges.forEach((edge) => {
const slug = edge.node.fields.slug;
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/blog-post.js`),
context: { slug: slug },
});
});
};
// Adds url slugs to the graph data response
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `posts` });
createNodeField({
node,
name: `slug`,
value: slug,
});
}
};
我的src/templates/blog-post.js
文件中有:
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';
export default function BlogPost({ data }) {
const post = data.markdownRemark;
const tags = (post.frontmatter.tags || []).map((tag, i) => {
return <li key={i}>#{tag}</li>;
});
return (
<Layout>
<article className="post">
<header>
<h1>{post.frontmatter.title}</h1>
<div className="meta">
<time>{post.frontmatter.date}</time>
<ul>{tags}</ul>
</div>
</header>
<section dangerouslySetInnerHTML={{ __html: post.html }} />
</article>
</Layout>
);
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
date(formatString: "DD-MMMM-YYYY")
tags
}
}
}
`;
我的markdown文件然后使用前题数据,如下所示:
---
title: Post title here
date: "2020-05-25T14:23:23Z"
description: "A small intro here"
tags: ["tag1", "tag2"]
---
Main post content would be here...