Skip to content

Instantly share code, notes, and snippets.

@vernonk
Created February 16, 2013 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vernonk/4969096 to your computer and use it in GitHub Desktop.
Save vernonk/4969096 to your computer and use it in GitHub Desktop.
Helper for using YAML Frontmatter in partials for Middleman. This expects HAML and a specific structuring and naming of partials (/source/partials/components/_COMPONENTNAME.html.haml) although it could be updated pretty easily. The goal behind this is to serve snippets of components (e.g. a "cta" snippet). This partial file would include frontma…
// Example of the partial for cta shown above
---
cta_class: default
cta_text: My Text!
cta_href: '#'
---
%a{:class => "#{cta_class}", :href => "#{cta_href"}"} #{cta_text}
// Include with just default data
= snippet "cta/_default"
// Overriding default data is easy
= snippet "cta/_default", {:cta_text => 'Click this yo', :cta_href => '/path/to/file.html'}
helpers do
def snippet(component, overrides = nil)
def colorize(text, color_code)
"\e[#{color_code}m#{text}\e[0m"
end
def red(text); colorize(text, 31); end
def green(text); colorize(text, 32); end
basepath = File.expand_path File.dirname(__FILE__)
exists = File.exists?(basepath << "/source/partials/components/" << component << ".html.haml")
if exists
# Read the partial, get the YAML, extend that hash with any overrides passed in
yaml_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m
content = File.read(basepath)
content = content.sub(yaml_regex, "")
data = YAML.load($1)
# Extend the hash so that any overrides are used instead of the defaults
if overrides != nil
overrides.each_key do |key|
data[key] = overrides[key]
end
end
else
puts red('[ERROR:]') + " Partial #{component} not found!"
return '<span style="color: red; font-weight: bold;">Error: Partial \'' + component + '\' not found!</span>'
end
##
# At this point, we have our data and know it exists
# Just load that partial baby
##
partial "/partials/components/" << component.sub("_", ""), :locals => data
end
end
@andreamoro
Copy link

Nice work. However, for some reason the reg expression provided doesn't seem to work with the newest version of MiddleMan.

To get it fixed, use this one yaml_regex = /---(.*[\s\S]*)---/m

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment