views:

460

answers:

3

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?

+7  A: 

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
Yeah.. It works :)Why you used first line of Code? <xsl:if test="@id='a'">
Wazdesign
The <xsl:if> ? I thought that you needed the comment to be included conditionally! Where's my vote/acceptance ?! ;-)
Cerebrus
Vote added. ;-) A conditional comment is included unconditionally. But IE evaluates the comment as a conditional -- if it evaluates to true, the code within gets executed.
Tomalak
Thanks. This is great.
i5m
A: 

what about if not ie. This method does not work.

carlos
A: 

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;--&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]]]>-->
Erik Töyrä