Last active
November 30, 2016 01:13
-
-
Save ChrisSki/b59ce6bf97f237474f3db5f4d0697d75 to your computer and use it in GitHub Desktop.
Jekyll - Parse YAML frontmatter in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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