tags:

views:

91

answers:

2

In XSLT, what is the preferred way to keep code DRY when it comes to 'if's?

At the moment I am doing this:

<xsl:if test="select/some/long/path">
    <element>
        <xsl:value-of select="select/some/long/path" />
    </element>
</xsl:if>

I would prefer to only write "select/some/long/path" once.

+6  A: 

I see your point. When the path is 200 chars long the code can get messy.

You could just add it to a variable

<xsl:variable name="path" select="select/some/long/path"/>

<xsl:if test="$path">    
   <xsl:value-of select="$path" />
</xsl:if>
Tommy
In this case the variable is a node so you can for example go: <xsl:variable name="path" select="select/some/long"/> <xsl:value-of select="$path/path" />
Alan Christensen
A: 

Where is the difference between:

<xsl:if test="select/some/long/path">
  <xsl:value-of select="select/some/long/path" />
</xsl:if>

and

<xsl:value-of select="select/some/long/path" />

? If it does not exist, value-of will output an empty string (i.e.: nothing). So why the test?

Tomalak
I was just keeping the example simple. I am actually using it like the following: <xsl:if test="select/some/long/path"> <element> <xsl:value-of select="select/some/long/path" /> </element> </xsl:if>
Nat Ryall
Formatted code was added to my original question.
Nat Ryall
Okay, thanks for elaborating.
Tomalak