You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Jekyll --watch在outline页面变更时重新生成自定义索引页?

Jekyll插件在--watch模式下无法自动更新索引页的解决方法

问题描述

我编写了一个Jekyll插件,用于为网站中使用outline布局的页面创建自定义索引,当前通过预渲染阶段的站点钩子实现。
使用Jekyll生成站点时,插件运行正常。但在开发阶段使用--watch模式时,编辑outline页面后,该页面会正常重新生成,但自定义索引页却不会更新。我推测这是因为索引页本身没有发生变更。
请问如何让Jekyll在必要时重新生成该索引页?我甚至可以接受在站点任意部分重新生成时,都重新生成该索引页,无论是否必要。

插件核心代码如下:

Jekyll::Hooks.register :site, :pre_render do |site, payload|
  destination = payload[:site][:pages].find {|p| p.permalink == '/ministry/outlines/'}
  # Generate content here...
  destination.content = destination.content.sub(/INSERT_PLUGIN_CONTENT_HERE/, generated_content.to_html(2))
end

解决方法

方案1:手动标记索引页为已修改

在预渲染钩子中,修改索引页的修改时间,让Jekyll认为它有变动,从而触发重新生成:

Jekyll::Hooks.register :site, :pre_render do |site, payload|
  destination = payload[:site][:pages].find {|p| p.permalink == '/ministry/outlines/'}
  # 强制更新索引页的修改时间
  destination.modified_at = Time.now
  # Generate content here...
  destination.content = destination.content.sub(/INSERT_PLUGIN_CONTENT_HERE/, generated_content.to_html(2))
end

方案2:监听outline页面变更,触发索引页更新

注册页面级钩子,当任意outline布局的页面被修改时,强制标记索引页需要重新生成:

# 监听outline页面的初始化/变更事件
Jekyll::Hooks.register :pages, :post_init do |page|
  next unless page.layout == 'outline'
  index_page = page.site.pages.find {|p| p.permalink == '/ministry/outlines/'}
  # 强制设置索引页为需要重新生成的状态
  index_page.instance_variable_set(:@regenerate, true) if index_page
end

# 保留原有的预渲染钩子逻辑
Jekyll::Hooks.register :site, :pre_render do |site, payload|
  destination = payload[:site][:pages].find {|p| p.permalink == '/ministry/outlines/'}
  # Generate content here...
  destination.content = destination.content.sub(/INSERT_PLUGIN_CONTENT_HERE/, generated_content.to_html(2))
end

方案3:全局强制重新生成索引页

如果不在意性能损耗,可以在站点读取完成后,直接将索引页加入到Jekyll的重新生成列表中,确保每次站点变更都更新索引页:

Jekyll::Hooks.register :site, :post_read do |site|
  destination = site.pages.find {|p| p.permalink == '/ministry/outlines/'}
  next unless destination
  # 强制索引页重新生成
  site.regenerator.add(destination.path)
end

# 原预渲染钩子逻辑不变
Jekyll::Hooks.register :site, :pre_render do |site, payload|
  destination = payload[:site][:pages].find {|p| p.permalink == '/ministry/outlines/'}
  # Generate content here...
  destination.content = destination.content.sub(/INSERT_PLUGIN_CONTENT_HERE/, generated_content.to_html(2))
end

内容的提问来源于stack exchange,提问作者Scott Severance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:00:21