Skip to content

Instantly share code, notes, and snippets.

@jletourneau
Created June 29, 2012 17:46
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 jletourneau/3019568 to your computer and use it in GitHub Desktop.
Save jletourneau/3019568 to your computer and use it in GitHub Desktop.
Haml helper for IE conditional comments visible to non-IE browsers
def iecc_visible(condition, &block)
output = capture_haml(&block)
"<!--[#{condition}]><!-->#{output.chomp}<!--<![endif]-->\n"
end
/[if lt IE 9]
.flash.error
%h1 Oh dear.
%p Have you considered upgrading your browser?
!= iecc_visible('if gte IE9') do
.flash.info
%h1 Congratulations!
%p Your browser is decent.
@jletourneau
Copy link
Author

The regular Haml syntax for IE conditional comments /[if foo] gives you this output:

<!--[if foo]>
  . . .
<![endif]-->

Non-IE browsers ignore the comment delimiters and everything between them. IE supports an alternate syntax for conditional comments that will not conceal their content from non-IE browsers:

<!--[if foo]><!-->
  . . .
<!--<![endif]-->

But there's no way (that I could find) of generating a conditional comment of this type using Haml's built-in IE conditional comment syntax. Hence the iecc_visible helper, under which one may indent a Haml block to be shown to any non-IE browser as well as any version of IE that passes the specified condition (provided as a string argument to the helper).

The typical use case for this would be in situations where one wished to have a chunk of code for reasonably standards-compliant browsers (non-IE browsers and recent versions of IE) and a different one for legacy versions of IE (e.g. the jQuery version jiu-jitsu under "Questions and Answers" in this post from the jQuery dev blog). This is shown in the "Haml usage" snippet above. Note that one must use Haml's raw output operator != rather than simply =, to prevent the content from being double-escaped by Haml.

The name iecc_visible is an inelegant contraction of "IE conditional comment, visible to non-IE browsers". Better name suggestions welcome.

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