Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a tag exists in XSLT?

Tags:

tags

xslt

I have the following template

<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>

I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?

like image 351
Manu Avatar asked Oct 12 '08 08:10

Manu


1 Answers

<xsl:if test="one">
  <h2>one</h2>
  <xsl:apply-templates select="one"/>
</xsl:if>
<!-- etc -->

Alternatively, you could create a named template,

<xsl:template name="WriteWithHeader">
   <xsl:param name="header"/>
   <xsl:param name="data"/>
   <xsl:if test="$data">
      <h2><xsl:value-of select="$header"/></h2>
      <xsl:apply-templates select="$data"/>
   </xsl:if>
</xsl:template>

and then call as:

  <xsl:call-template name="WriteWithHeader">
    <xsl:with-param name="header" select="'one'"/>
    <xsl:with-param name="data" select="one"/>
  </xsl:call-template>

But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple <h2>...</h2> I'd be tempted to leave it inline.

If the header title is always the node name, you could simplifiy the template by removing the "$header" arg, and use instead:

<xsl:value-of select="name($header[1])"/>
like image 87
Marc Gravell Avatar answered Oct 11 '22 01:10

Marc Gravell