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

如何使用front_matter_parser保留YAML数组的2空格缩进?

解决FrontMatter数组缩进丢失问题

问题出在默认的YAML.dump输出格式上,它不会给数组元素添加缩进。要保留2空格缩进,我们可以利用Ruby的Psych库(YAML的默认后端)的自定义缩进配置来实现。

修改后的代码

require 'front_matter_parser'
require 'psych'

class FrontMatterUpdater
  def self.run(path)
    parsed = FrontMatterParser::Parser.parse_file(path)
    front_matter = parsed.front_matter
    
    front_matter['redirect_from'] = Array(front_matter['redirect_from'])
    front_matter['redirect_from'] << 'new_entry2'
    front_matter['redirect_from'].uniq!
    
    # 配置YAML输出的缩进规则:整体缩进2空格,数组元素额外缩进2空格
    yaml_content = Psych.dump(front_matter, indentation: 2, array_indentation: 2).chomp
    new_content = [yaml_content, '---', "\n\n", parsed.content].join
    
    File.write(path, new_content)
  end
end

FrontMatterUpdater.run('test.md')

效果说明

执行后test.md的FrontMatter会保留数组的2空格缩进:

---
redirect_from:
  - new_entry0
  - new_entry1
  - new_entry2
--- 

备选方案(全局配置)

如果需要在多个地方统一缩进规则,可以设置Psych的全局默认选项,这样不用每次dump都传参数:

require 'front_matter_parser'
require 'psych'

# 全局设置YAML缩进规则
Psych.default_options[:indentation] = 2
Psych.default_options[:array_indentation] = 2

class FrontMatterUpdater
  def self.run(path)
    parsed = FrontMatterParser::Parser.parse_file(path)
    front_matter = parsed.front_matter
    
    front_matter['redirect_from'] = Array(front_matter['redirect_from'])
    front_matter['redirect_from'] << 'new_entry2'
    front_matter['redirect_from'].uniq!
    
    yaml_content = YAML.dump(front_matter).chomp
    new_content = [yaml_content, '---', "\n\n", parsed.content].join
    
    File.write(path, new_content)
  end
end

FrontMatterUpdater.run('test.md')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:30:43