"[!IE]"Haml的条件评论

Bro*_*ate 30 haml internet-explorer conditional

在HAML文档中,我有:

/[if IE]
  This is IE
/[if !IE]
  This is not IE
Run Code Online (Sandbox Code Playgroud)

第一个条件在IE中正确评估(可能在Firefox和Chrome中,因为"这是IE"在这些浏览器中不呈现).但是,第二个条件似乎没有在Firefox或Chrome中正确评估,因为"这不是IE"不会呈现.

我猜我做错了什么.有任何想法吗?

mat*_*att 92

使用IE条件注释时,您需要注意两种不同的类型.首先,当整个内容在HTML注释中(在<!--和之间-->)时,IE会因为条件而读取它:

<!--[if IE]>
  This is inside a HTML comment, so most browsers will ignore it, but IE will
  interpret it.
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

另一种类型不是单一评论,而是浏览器会看到的一些内容,包含两条注释,会让IE忽略它:

<!--[if !IE]> -->
  This is not a HTML comment, so browsers should see it, but IE will ignore it.
<!-- <![endif]-->
Run Code Online (Sandbox Code Playgroud)

(SO的代码突出显示了差异 - 在顶部的一切都是灰色的,因为它是所有评论,但在这一个文本更暗,因为它不是评论).

Haml对IE条件注释的支持仅对创建第一种类型有用,因为它是创建块注释的语法的一部分.如果您尝试将它用于第二种(就像您在这里一样),您会得到类似的结果:

<!--[if !IE]>
  This is inside a HTML comment, so other browsers will ignore it.
  IE will also ignore it, as the conditional states !IE.
  So everything ignores it.
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

这实际上是一个无条件的评论.

[if !IE]在Haml中使用该类型,您可能必须手动执行:

%p Some other content
<!--[if !IE]> -->
%p
  Here's some content that shouldn't appear in IE.
<!-- <![endif]-->
Run Code Online (Sandbox Code Playgroud)

您也可以使用Haml surround助手,如下所示:

%p Some other content
=surround '<!--[if !IE]> -->', '<!-- <![endif]-->' do
  %p
    Here's some content that shouldn't appear in IE.
Run Code Online (Sandbox Code Playgroud)

(如果你正在使用Rails,那么你需要html_safe在字符串上使用,即surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do).

如果您经常使用它,那么创建一个包装此调用的辅助方法可能是值得的surround.

  • 您可能需要"<! - [if!IE]> - >".html_safe以避免条件仅显示为文本 (4认同)
  • 这是一个很好的答案.我很惊讶你没有得到更多的赞成.+1! (2认同)