Skip to content

Instantly share code, notes, and snippets.

@ChrisSki
Last active November 30, 2016 01:13
Show Gist options
  • Save ChrisSki/b59ce6bf97f237474f3db5f4d0697d75 to your computer and use it in GitHub Desktop.
Save ChrisSki/b59ce6bf97f237474f3db5f4d0697d75 to your computer and use it in GitHub Desktop.
Jekyll - Parse YAML frontmatter in a string
module Jekyll
module YamlParser
def yamlparser(string = '', options = {})
options = {delimiter: '---', parser: YAML, remove: nil}.merge(options)
# convert string params to symbols
options = options.inject({}) {|memo, (k,v)| memo[k.to_sym] = v; memo}
@delimiter = options[:delimiter]
@parser = options[:parser]
@remove = options[:remove]
# if you have extra stuffs in front of your YAML, like ```
unless @remove.nil?
string.tr!(@remove, '')
end
res = [{},'']
res[1] = string.lstrip.gsub(/#{@delimiter}(.*)#{@delimiter}/m) do |match|
res[0] = @parser.load($~.captures.first.strip)
''
end.strip
res
end
end
end
Liquid::Template.register_filter(Jekyll::YamlParser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment