Creating conditional comments with XSLT?

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?

Answers


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.


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

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


Need Your Help

How can Print Preview be called from Javascript?

javascript printing

I have a page that is supposed to launch the Print Preview page onload.