thilemann
thilemann

Reputation: 397

Wrapping a for-each in div for every nth element

I'm having trouble with figuring out how to wrap the contents of a for-each in a div, where each div contains 4 elements each.

Below, you'll find a much simplified version of my XSLT:

  <xsl:template match="/">
        <div class="container"><!-- have to be repeated for every 4 elements from the for-each -->
          <xsl:for-each select="$currentPage/GalleriListe/descendant::* [@isDoc] [not(self::GalleriListe)]">
              <div>...</div>
          </xsl:for-each>
        </div>
  </xsl:template>

Any ideas? Thanks!

Upvotes: 0

Views: 827

Answers (1)

Mitya
Mitya

Reputation: 34566

You didn't post your XML, so I've used a simplified one for this answer. It's a bit hacky, and there might be a more elegant way. You can test it at this XMLPlayground session

<!-- declare how many items per container -->
<xsl:variable name='num_per_div' select='4' />

<!-- root - kick things off -->
<xsl:template match="/">
    <xsl:apply-templates select='root/node' mode='container' />
</xsl:template>

<!-- iteration content - containers -->
<xsl:template match='node' mode='container'>
    <xsl:if test='position() = 1 or not((position()-1) mod $num_per_div)'>
        <div>
            <xsl:variable name='pos' select='position()' />
            <xsl:apply-templates select='. | following-sibling::*[count(preceding-sibling::node) &lt; $pos+(number($num_per_div)-1)]' />
        </div>
    </xsl:if>
</xsl:template>

<!-- iteration content - individual items -->
<xsl:template match='node'>
    <p><xsl:value-of select='.' /></p>
</xsl:template>

Upvotes: 1

Related Questions