这是一个相当小众的问题,但是......我运行一个在 Jekyll 上运行的博客,并且我经常发帖。为了保持我的编辑理智,我定期存档帖子,并且这些存档的帖子有一个非常严格的结构。但是,我花了整整一年才归档。
这会伤害到其他帖子的链接。我曾经能够绝对引用文件名(根据 jekyll markdown 内部链接),但这似乎已被弃用:
Deprecation: A call to '{% post_url 2018-09-06-peppermint %}' did not match a post using the new matching method of checking name (path-date-slug) equality. Please make sure that you change this tag to match the post's name exactly.
现在,如果我必须包含文件的完整路径,那么当我归档当年的帖子时,我必须解析全年的所有帖子并更新它们之间的任何链接以包含其新文件路径存档位置,根本失去了使用此工具的意义。考虑到我很少更改 URL 结构,直接链接到该页面实际上会更好。
是否有更好的不依赖于文件结构的内部链接解决方案,允许移动文件而无需更新该文件的每个链接?
文件结构示例:
_posts
-2018
-post1
-post2
-etc
-Archive
-2017
-2016
如果没有更好的答案,我可能只能重新使用绝对外部链接。
创建一个 post_url.html 文件并写入以下内容:
{% include post_url.html slug="2018-09-06-peppermint" %}
包含(称为 post_url.html)应该找到具有正确 slug 的帖子并回显链接,如下所示:
{% assign link = site.posts | where:'slug',include.slug %}
<a href="{{ link[0].url }}">{{ link[0].title }}</a>
你必须解析帖子吗?对所有文件进行简单的搜索和替换,查找
(/2018/
并替换为 (/Archive/2018/
应该可以解决问题(如果您使用 Markdown 链接)。这应该只需要几秒钟。
可以创建一个自定义标签,而不是使用“path-date-slug”,而使用“date-slug”作为检查名称的匹配方法。
我在我的博客中实现了这种方法,因为就我而言,我永远不会有两个具有相同日期和别名的帖子。我描述了以下步骤:
如果您的博客中不存在,请创建一个目录
_plugins
(与 _posts
处于同一级别),然后创建一个新的文本文件 _plugins/post_url_short_tag.rb
注意:如果您使用 GitHub 页面,此方法可能在开发中有效,但在部署时您会发现挑战 - 请参阅此处。
myblog
├── ...
├── _plugins
│ └── post_url_short_tag.rb
├── _posts
└── ...
新文件的内容应如下
# _plugins/post_url_short_tag.rb
module Jekyll
class PostUrlShortTag < Liquid::Tag
def initialize(tag_name, input, tokens)
super
@input = input.strip
end
def render(context)
site = context.registers[:site]
date, slug = @input.split('-')
post = site.posts.docs.find { |p| p.date.strftime('%Y-%m-%d') == date && p.data['slug'] == slug }
post.url if post
end
end
end
Liquid::Template.register_tag('post_url_short', Jekyll::PostUrlShortTag)
由于您的旧帖子可能有许多将它们连接在一起的链接,因此最好使用新帖子测试标签:
_posts/2024-04-05-new-post.markdown
创建新帖子(空)。_posts/2018-09-06-peppermint
)中,使用自定义标签创建对新帖子的引用:<!-- _posts/2018-09-06-peppermint -->
<!-- ... -->
{% post_url_short 2024-04-05-new-post.markdown %}
_posts/subdir/2024-04-05-new-post.markdown
,然后重新启动网站(停止提供服务,然后重新启动)。post_url
标签为 post_url_short
一旦您确认此方法适合您(在开发和生产中),您将需要:
post_url
替换为 post_url_short
(如果帖子/链接很多,一个简单的 Python 脚本 可能会有所帮助)。post_url_short
。