pethel
pethel

Reputation: 5537

Adding html class according to xslt statement

xslt is pretty new for me. Is it possible to do something similar to my code below. I know it is possible in other template languages.

  <div class="<xsl:if test="position()=1">myclass</xsl:if>">Hello</div> 

Upvotes: 4

Views: 4458

Answers (2)

Peter
Peter

Reputation: 1796

It should be something like this:

<xsl:variable name="myclass" select="variablenode" />
    
<div class="adf">
<xsl:if test="yournode[position()=1]">
    <xsl:value-of select="$myclass"/>
</xsl:if>
Hello</div> 

But please give us your source XML, the XSLT you have so far and the expected output. Otherwise we can only guess.

Upvotes: 1

Daniel Haley
Daniel Haley

Reputation: 52858

You could wrap an xsl:attribute in an xsl:if...

    <div>
        <xsl:if test="position()=1">
            <xsl:attribute name="class">myclass</xsl:attribute>
        </xsl:if>
        <xsl:text>Hello</xsl:text>
    </div>

Also, in XSLT 2.0, you can write the xsl:attribute like this:

<xsl:attribute name="class" select="'myClass'"/>

Another XSLT 2.0 option, if you don't mind having an empty class="", is to use an if in an AVT (Attribute Value Template):

<div class="{if (position()=1) then . else ''}">...</div>

The then may vary depending on context.

Upvotes: 7

Related Questions