在Haml中的"[!IE]"条件注释

30
在一个 HAML 文档中,我有以下内容:
/[if IE]
  This is IE
/[if !IE]
  This is not IE

第一个条件在IE中正确评估(并且可能在Firefox和Chrome中也是如此,因为“This is IE”不会在这些浏览器中呈现)。然而,第二个条件似乎在Firefox或Chrome中无法正确评估,因为“This is not IE”没有呈现。

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


实际生成的HTML是什么? - Andrew Marshall
<!--[if IE]> This is IE <![endif]--> <!--[if !IE]> This is not IE <![endif]--> - BronzeGate
4个回答

93
当使用IE条件注释时,您需要了解两种不同的类型。首先,当整个内容位于HTML注释(在<!---->之间)中,但是由于条件,IE将读取它:
<!--[if IE]>
  This is inside a HTML comment, so most browsers will ignore it, but IE will
  interpret it.
<![endif]-->

另一种类型不是单个注释,而是被两个注释包围的浏览器会忽略的内容。
<!--[if !IE]> -->
  This is not a HTML comment, so browsers should see it, but IE will ignore it.
<!-- <![endif]-->

(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]-->

这实际上是一个无条件注释。

为了在 Haml 中使用 [if !IE] 类型,您可能需要手动完成:

%p Some other content
<!--[if !IE]> -->
%p
  Here's some content that shouldn't appear in IE.
<!-- <![endif]-->

您还可以使用 Haml 的 surround 助手,例如:

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

如果您使用的是Rails,则需要在字符串上使用html_safe,即:surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do

如果您经常使用这个方法,可能值得创建一个帮助程序方法来包装对surround的调用。


2
这是一个很棒的答案。我很惊讶你没有得到更多的赞同。点赞! - sscirrus
4
你可能需要使用 "<!--[if !IE]> -->".html_safe,以避免条件语句被显示为纯文本。 - TalkingQuickly
请确保您尊重@matt选择的空格 - 我曾尝试在注释标记之间缩进%p,但那样不起作用。 - Jenn
@Jenn 我对空格完全没有任何尊重 - IE实际上因为一个空格字符而在我的网站上完全崩溃了,显然它无法解析条件语句中的空格! - Jon Cairns
@matt,我在理解你说的内容时遇到了一些问题,但我找到了解决方法并将其发布为答案。你能否请看一下并告诉我是否有做错什么? - Syed

1

已经有答案了,但对于那些寻找简短版摘要的人:

/[if IE]
  This will only be rendered in IE

/[if lte IE 8]
  This will only be rendered in IE 8 or less

= surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do
  This will only be rendered in NON-IE browsers.

1

查看条件列表:

!!!
:plain
  <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--><!--[if IE 7]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--><!--[if IE 8]><html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]--> <!--[if gt IE 9]><!-->
%html.no-js{:lang => 'en'}
  / <![endif]

  %head
    %title Yinlang

0

我正在做一个 Rails 应用程序,我在按照 @matt 在他的回答中建议的步骤进行时发现了一些问题,我发现以下问题:

HAML

!!!
= surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do
  %html.no-js{:lang => 'en'}
  %head
  %body

以下是浏览器如何渲染HTML(在最后没有结束标签的情况下,在声明行添加结束标签)

<!DOCTYPE html>
<!--[if !IE]> --><html class='no-js' lang='en'></html>
<head>..</head>
<body>..</body>

所以,这是对我来说运行良好的代码。

!!!
:plain
  <!--[if !IE]><!-->
%html.no-js{:lang => 'en'}
  / <![endif]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接