12

I want to create conditional comments in XSLT.

But when I use this:

<!-- [If IE7] [endif] -->

in an <xsl:comment>, XSLT removes it from the output when it is rendered.

Is there any way to create conditional comments in XSLT?

Wayne
  • 59,728
  • 15
  • 131
  • 126
Wasim Shaikh
  • 6,880
  • 18
  • 61
  • 88

3 Answers3

22

Simply use an <xsl:comment> tag and include your comment within the tag.

For example:

<xsl:if test="@id = '1'">
  <xsl:comment>
    <![CDATA[[if IE]><![endif]]]>
  </xsl:comment>
</xsl:if>

Taming Your Multiple IE Standalones is a great article on this subject.

Cerebrus
  • 25,615
  • 8
  • 56
  • 70
6

The above solution assumes that the content inside the conditional comment does not contain any XSLT parameters. In the example below we're having a parameter $DATA_ROOT_PATH that should be processed to give us the correct location of a CSS file. In this case <xsl:comment/> is not suitable. We must use <xsl:text/> and disable the output escaping.

The example here will include the CSS file only if we're using IE7.

<xsl:text disable-output-escaping="yes">&lt;!--[if IE 7]&gt;</xsl:text>
  <link rel="stylesheet" type="text/css" href="{$DATA_ROOT_PATH}/resources/css/ie7.css" media="screen"/>
<xsl:text disable-output-escaping="yes">&lt;![endif]--&gt;</xsl:text>

The code example would generate output like so if $DATA_ROOT_PATH = /example:

<!--[if IE 7]>
  <link rel="stylesheet" type="text/css"
        href="/example/resources/css/ie7.css"
        media="screen" />
<![endif]-->
  • 1
    You wrote _" is not suitable"_, but it is as per http://www.w3.org/TR/xslt#section-Creating-Comments : _"` `"_ It means that you can use any content template inside `xsl:comment` instruction as long as it output nothing else than text nodes. –  Apr 15 '11 at 20:05
  • This is a perfectly valid scenario, when you need to process the contents of the conditional comment further. There is a typo with the closing tag though: There are two extra `]]` characters after the endif. Correctly it should say: `<![endif]-->` – aron.lakatos Oct 31 '16 at 17:41
0

This was the only way I was able to get my ie stylesheet to be applied:

    <xsl:comment>[if IE]>
      &lt;link rel="stylesheet" type="text/css" href="ie.css" />
      &lt;![endif]</xsl:comment>

I had to make sure there is no space between my text and the xsl:comment opening/closing tags