tags:

views:

140

answers:

3

I am trying to create a simple inventory of items in a Sitecore website using an xslt. The problem is that I can't find a way to test whether an item has descendant items beneath it.

It's easy to get the top level set like this:

<xsl:template match="*" mode="main">
<table width="100%" class="alternating">
   <xsl:for-each select="./item">
        <tr>
 <td width="100px"><sc:image field="Image" mh="100" mw="100" /></td>
<td style="vertical-align:top"><h2><sc:text field="Title"/></h2></td>
<td style="vertical-align:top"><xsl:value-of select="sc:path(.)" /></td>
        </tr>
   </xsl:for-each>
</table>
</xsl:template>

This creates a nice, flat table of the main image, the title and the path of each item just below where you start. The problem is that I can’t find a way to easily test whether one of these items has descendants. That would make the code look something like this:

<xsl:template match="*" mode="main">
<table width="100%" class="alternating">
   <xsl:for-each select="./item">
        <tr>
 <td width="100px"><sc:image field="Image" mh="100" mw="100" /></td>
<td style="vertical-align:top"><h2><sc:text field="Title"/></h2></td>
<td style="vertical-align:top"><xsl:value-of select="sc:path(.)" /></td>
<td>
    <!—test whether the item has descendants -->
    <xsl:if test=?????>
     <!—loop through descendant items -->
     <xsl:for-each select="./item">
     Render information about each descendant item
     </xsl:for-each>
    </xsl:if>
</td>
        </tr>
   </xsl:for-each>
</table>
</xsl:template>
+1  A: 

There is no need to test for descendents. Just use:

...
<td>        
<!-- loop through descendant items if any -->        
<xsl:for-each select="./item">        
<!-- Render information about each descendant item -->      
</xsl:for-each>    
</xsl:if>
</td>
...

If there are no descendents nothing will be output for that node.

Rashmi Pandit
A: 

Rashmi is correct, the for-each should not execute if there are no children.

But incidentally, just to answer the question, you can perform a test

<xsl:if test="count(item) != 0">
Mark Cassidy
A: 

You might want to test for descendants if you are rendering a list and don't want the wrapping tags when that aren't any descendants then you may want the if:

<xsl:if test="count(./item) &gt; 0">
  <ul>
    <xsl:for-each select="./item">
      <li>
         <!-- content here -->
      </li>
    </xsl:for-each>
  </ul>
</xsl:if>
Michael Edwards