Skip to content

Instantly share code, notes, and snippets.

@sunny
Created February 17, 2009 19:06
Show Gist options
  • Save sunny/65908 to your computer and use it in GitHub Desktop.
Save sunny/65908 to your computer and use it in GitHub Desktop.
# Helper that adds inline CSS styles to the tags you want from an html string.
# Examples:
# add_styles("<p>Ohi</p>", :p => 'color:red') # => '<p style="color:red">Ohi</p>'
# add_styles("<p>Ohi</p>", :p => {:color => 'red'}) # => '<p style="color:red">Ohi</p>'
def add_styles(html, tags)
html = html.dup
tags.each do |tag, style|
style = style.map{|k,v| "#{k}:#{v}"}.join(';') unless style.is_a?(String)
html.gsub! /<(#{tag}.*?)(?: style="(.*?)")?(.*?)>/,
"<\\1 style=\"#{style};\\2\"\\3>"
end
html
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment