如何将RSS XML转换为可用YAML?解决Jekyll过滤器返回字符串问题
Jekyll自定义RSS过滤器返回字符串无法访问属性的解决方法
问题描述
我用自定义Jekyll过滤器从RSS源拉取XML并转成YAML用于页面开发,功能看似能运行,但返回的YAML是不可读的字符串,无法正常访问其属性。具体测试情况如下:
使用过滤器的代码
{%- assign endpoint = 'https://paragraph.xyz/api/blogs/rss/@dylsteck.eth' -%} {%- assign data = endpoint | getrss -%}
过滤器实现代码(getrss.rb)
require 'net/http' module Jekyll module GetRSS def getrss(input) xml = Net::HTTP.get_response(URI.parse(input)).body Hash.from_xml(xml).to_yaml end end end Liquid::Template.register_filter(Jekyll::GetRSS)
测试场景与结果
场景1:尝试访问
data.rss属性<script>console.log({{data.rss | jsonify}})</script>输出:
null场景2:直接输出
data<script>console.log({{data | jsonify}})</script>输出(截取核心内容):
--- rss: version: '2.0' xmlns:dc: http://purl.org/dc/elements/1.1/ xmlns:content: http://purl.org/rss/1.0/modules/content/ channel: title: Next in Tech link: https://paragraph.xyz/@dylsteck.eth # 省略其余内容场景3:查看
data.rss的类型<script>console.log(typeof {{data.rss | jsonify}})</script>输出:
string
可见返回的是带---开头的纯字符串,无法直接通过点语法访问属性,需要将其转换为Liquid可处理的结构化对象。
解决方案
问题根源在于过滤器里的to_yaml调用——它把XML转换后的Ruby Hash变成了YAML格式的字符串,而Liquid只能直接处理Ruby对象(比如Hash、Array),无法自动解析字符串为结构化数据。
修改getrss.rb,直接返回Hash.from_xml(xml)的结果即可:
require 'net/http' module Jekyll module GetRSS def getrss(input) xml = Net::HTTP.get_response(URI.parse(input)).body # 直接返回Ruby Hash,Liquid会自动识别为可访问的结构化对象 Hash.from_xml(xml) end end end Liquid::Template.register_filter(Jekyll::GetRSS)
修改后,data就会变成Liquid可处理的对象,你可以正常访问data.rss.channel.title、data.rss.item等属性。比如再次运行场景1的代码,会输出正确的JSON对象而非null。
额外注意事项
依赖检查:
Hash.from_xml来自active_support库,如果你的Jekyll环境没有这个依赖,需要在项目的Gemfile中添加:gem 'active_support'然后执行
bundle install安装依赖。异常处理:建议给HTTP请求添加异常捕获,避免RSS源不可用或请求失败时导致构建中断:
def getrss(input) uri = URI.parse(input) response = Net::HTTP.get_response(uri) if response.is_a?(Net::HTTPSuccess) Hash.from_xml(response.body) else # 请求失败时返回空Hash,避免构建报错 {} end rescue => e Jekyll.logger.error "GetRSS过滤器错误: #{e.message}" {} end
内容的提问来源于stack exchange,提问作者Jack Hanna
相关产品推荐
相关产品推荐

