Re: [xsl] Reg apply-templates and for-each

Subject: Re: [xsl] Reg apply-templates and for-each
From: David Carlisle <davidc@xxxxxxxxx>
Date: Thu, 1 Sep 2005 09:52:20 +0100
> but can any
> one tell me when should one go for xsl:apply-templates and when for
> xsl:for-each.


<xsl:for-each select="zzzz">
.....
</xsl:for-each>

is the same thing (more or less) as

<xsl:apply-templates select="zzz" mode="yyy"/>

<xsl:template match="node()" mode="yyy">
....
</xsl:for-each>

So, as you see, for-each is really just a restricted form of
apply-templates, and so which to use is mainly a matter of taste.

Note the main thing about for-each is that each node that is selected
(zzzz here) gets the same code applied (..... here). If that is what is
required, using for-each which makes this explict is often clearer.

In the apply-templates case, typically different types of node that
are selected would have different templates matching. Note that
apply-templates is only equivalent to for-each in the case that there
is a single template that matches _all_ the selected nodes.

There are other differences due to the way the scope of variables etc
work, which means that it is sometiomes more convenient to use or-each
and have direct access to variables in the current template rather
than use apply-templates, and have to explictly pass the variables as
parameters to the template. But generally using apply-templates is
betetr as it makes it easier to modify/maintain your code by adding new
templates, or importing stylesheets to override specific templates.
Stylesheets taht have just one bug template with lots of for-each groups
are harder to customise as if youy import the stylesheet you have to
replace entire template if you need to change any part of it.

David

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________

Current Thread