Aswathy S
Aswathy S

Reputation: 731

How to add style attribute in xsl by @variable

I have a variable @expectedLength. I need to assign it to a style attribute.

            <xsl:if test="@expectedLength">
               <xsl:attribute name="style">
                  <xsl:value-of select="'width:200px'"/>
               </xsl:attribute>
            </xsl:if>

I need to replace 200 with the value of @expectedLength. How can I use the variable?

Upvotes: 0

Views: 530

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

You could change your snippet to

<xsl:if test="@expectedLength">
  <xsl:attribute name="style">width: <xsl:value-of select="@expectedLength"/>;</xsl:attribute>
</xsl:if>

That should work with any version of XSLT.

In XSLT 2 and later you can also use the select expression

<xsl:if test="@expectedLength">
  <xsl:attribute name="style" select="concat('width: ', @expectedLength, ';')"/>
</xsl:if>

I would prefer to and suggest to set up a template

<xsl:template match="@expectedLength">
  <xsl:attribute name="style" select="concat('width: ', @expectedLength, ';')"/>
</xsl:template>

and then to make sure higher up that any attribute nodes are processed.

Upvotes: 1

Related Questions