IE conditional comment helper for Rails 1

Posted by tieg Thu, 05 Apr 2007 00:10:00 GMT

These days, now that we have IE7, it’s common for those of us developing for the web to use conditional comments instead of CSS hacks to make sure our sites look good in different versions of Internet Explorer. (Or to pass anything else exclusively to IE)

I find myself using them on a regular basis, so here’s a little helper you can throw in your ./helpers/application.helper.rb to Rubify some of that commentage:

  # info at http://msdn.microsoft.com/workshop/author/dhtml/overview/ccomment_ovw.asp
  def conditional_comments(options={}, &proc)
    inverse    = options[:inverse] || ''
    comparison = options[:comparison] ? " #{options[:comparison]}" : ''
    version    = options[:version] || 5
    concat("<!--[if#{comparison} #{inverse}IE #{version}]>\n#{yield}\n<![endif]-->", proc.binding)
  end

Just put it in an ERb evaluation block and feed it a block of output:

<% conditional_comments :comparison => 'gte', version => 5.0 do
      stylesheet_link_tag 'layout_ie', 'typography_ie'
   end %>

Output:

<!--[if gte IE 5.0]>
<link href="/stylesheets/layout_ie.css" media="screen" rel="Stylesheet" type="text/css" />
<link href="/stylesheets/typography_ie.css" media="screen" rel="Stylesheet" type="text/css" />
<![endif]-->

It might be a little too much abstraction or processing for your tastes, but I was just a little sick of seeing the comments in every header. Yatta!