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

求Jekyll插件读取ICS文件并暴露给Liquid变量的示例

Jekyll插件示例:读取ICS文件并注入site变量

步骤1:创建Jekyll生成器插件

在你的Jekyll项目的_plugins目录下创建文件ics_reader.rb,代码如下:

require 'icalendar'
require 'open-uri'

module Jekyll
  class IcsReaderGenerator < Generator
    safe true
    priority :high

    def generate(site)
      # 支持本地文件路径或远程URL,可通过_config.yml配置
      ics_source = site.config['ics_source'] || '_data/calendar.ics'

      begin
        # 读取ICS内容
        ics_content = if ics_source.start_with?('http')
                        URI.open(ics_source).read
                      else
                        File.read(File.join(site.source, ics_source))
                      end

        # 解析ICS事件并格式化
        calendars = Icalendar::Calendar.parse(ics_content)
        formatted_events = calendars.first.events.map do |event|
          {
            title: event.summary,
            start: event.dtstart,
            end: event.dtend,
            description: event.description,
            location: event.location
          }
        end

        # 将数据存入site.data,Liquid模板可通过site.data.calendar_events访问
        site.data['calendar_events'] = formatted_events
      rescue => e
        Jekyll.logger.error "ICS解析失败: #{e.message}"
        site.data['calendar_events'] = []
      end
    end
  end
end

步骤2:配置ICS源

在项目根目录的_config.yml中添加ICS源配置:

ics_source: "https://example.com/your-calendar.ics" # 或本地路径如"_data/calendar.ics"

步骤3:在Liquid模板中调用数据

在模板文件(比如calendar.html)中遍历事件数据:

<h2>近期活动</h2>
<ul>
  {% for event in site.data.calendar_events %}
    <li>
      <strong>{{ event.title }}</strong><br>
      开始时间: {{ event.start | date: "%Y-%m-%d %H:%M" }}<br>
      {% if event.end %}结束时间: {{ event.end | date: "%Y-%m-%d %H:%M" }}<br>{% endif %}
      {% if event.location %}地点: {{ event.location }}<br>{% endif %}
      {% if event.description %}简介: {{ event.description | strip_html }}{% endif %}
    </li>
  {% empty %}
    <li>暂无活动</li>
  {% endfor %}
</ul>

注意事项

  • 先安装依赖gem:在项目根目录运行bundle add icalendar
  • 插件优先级设为:high,确保在模板渲染前完成数据解析
  • 加入异常处理,避免ICS文件读取/解析失败导致站点构建中断

内容的提问来源于stack exchange,提问作者Chris Valentine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 10:45:33