Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific template for the first element

I have a template:

<xsl:template match="paragraph">
    ...
</xsl:template>

I call it:

<xsl:apply-templates select="paragraph"/>

For the first element I need to do:

<xsl:template match="paragraph[1]">
    ...
    <xsl:apply-templates select="."/><!-- I understand that this does not work -->
    ...
</xsl:template>

How to call <xsl:apply-templates select="paragraph"/> (for the first element paragraph) from the template <xsl:template match="paragraph[1]">?

So far that I have something like a loop.


I solve this problem so (but I do not like it):

<xsl:for-each select="paragraph">
    <xsl:choose>
        <xsl:when test="position() = 1">
            ...
            <xsl:apply-templates select="."/>
            ...
        </xsl:when>
        <xsl:otherwise>
            <xsl:apply-templates select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:for-each>
like image 383
Kalinin Avatar asked May 19 '10 07:05

Kalinin


2 Answers

One way to do this could be to make use of a named template, and have both the first and other paragraphs calling this named template.

<xsl:template match="Paragraph[1]">
   <!-- First Paragraph -->
   <xsl:call-template name="Paragraph"/>
</xsl:template>

<xsl:template match="Paragraph">
   <xsl:call-template name="Paragraph"/>
</xsl:template>

<xsl:template name="Paragraph">
   <xsl:value-of select="."/>
</xsl:template>

Another way, is to call apply-templates separately for the first paragraph and other paragraphs

  <!-- First Paragraph -->
  <xsl:apply-templates select="Paragraph[1]"/>

  <!-- Other Paragraphs -->
  <xsl:apply-templates select="Paragraph[position() != 1]"/>
like image 88
Tim C Avatar answered Nov 07 '22 00:11

Tim C


Name your generic paragraph template, then invoke it by name from the paragraph[1] template:

<xsl:template match="paragraph" name="paragraph-common"> 
    ... 
</xsl:template>

<xsl:template match="paragraph[1]">
    ...
    <xsl:call-template name="paragraph-common"/>
    ...
</xsl:template>

A template can have both a match and a name attribute. If you set both, you can invoke the template both by xsl:apply-templates and by xsl:call-template.

like image 28
markusk Avatar answered Nov 06 '22 23:11

markusk