multiple items in loop
This is an open discussion with 8 replies, filed under XSLT.
Search
Take a look at this Stack Overflow answer, I think it should work:
XSLT to transform list into table with columns determined dynamically
Thanks ashooner,
I came up with this xslt that does the job:
<xsl:apply-templates select="blog/entry[position() mod 4 = 1]"/> <xsl:template match="entry"> <div class="container"> <xsl:call-template name="header"/> <xsl:for-each select="following-sibling::entry[position() < 4]"> <xsl:call-template name="header"/> </xsl:for-each> </div> </xsl:template> <xsl:template name="header"> <h1><xsl:value-of select="title"/></h1> </xsl:template>
Nice. I vote this goes into the XSLT Utilities, I'm sure others will find it useful.
Nice. I vote this goes into the XSLT Utilities, I'm sure others will find it useful.
+1
When I'm writing XSLT I try to keep it as consistent as possible, in this case not mixing for-each
and apply-templates
too much.
Also, I see using named templates and then passing the context node as a param as bad practice; that's what matching templates are made for.
So my suggestion would be something like (notice the mode
attribute):
<xsl:apply-templates select="blog/entry[position() mod 4 = 1]" mode="group" /> <xsl:template match="entry" mode="group"> <div class="container"> <xsl:apply-templates select=". | following-sibling::entry[position() < 4]" mode="content"> </div> </xsl:template> <xsl:template name="entry" mode="content"> <h1><xsl:value-of select="title"/></h1> <xsl:copy-of select="text/*" /> </xsl:template>
Thanks Nils,
That looks better, my xslt skills just did'nt reach far enough for that, but getting there!
I will submit this to the utilities, what would be a good name?
I was thinking about 'multi-item loop'? Any suggestions?
What about "Group items" or "Group by position"?
Group items it is.... :)
Create an account or sign in to comment.
I am trying to loop 4 items in a for each loop (or applying a template for 4 items) and then take the next 4 items... normally the loop is applied per item.
here's the xml:
And the desired result:
So i am trying to wrap each 4 items in a div container...
Anyone knows how to accomplish this?