What are the differences between ‘call-template’ and ‘apply-templates’ in XSL


I am new in XSLT so I'm little bit confused about the two tags,

<xsl:apply-templates name="nodes">


<xsl:call-template select="nodes"> 

So can you list out the difference between them?

Best Solution

<xsl:call-template> is a close equivalent to calling a function in a traditional programming language.

You can define functions in XSLT, like this simple one that outputs a string.

<xsl:template name="dosomething">
  <xsl:text>A function that does something</xsl:text>

This function can be called via <xsl:call-template name="dosomething">.

<xsl:apply-templates> is a little different and in it is the real power of XSLT: It takes any number of XML nodes (whatever you define in the select attribute), processes each of them (not necessarily in any predefined order), somebody could say that apply-templates works like a loop, but this is not exactly the case, as the nodes may be processed in any order, even in parallel, and finds matching templates for them:

<!-- sample XML snippet -->
  <foo /><bar /><baz />

<!-- sample XSLT snippet -->
<xsl:template match="xml">
  <xsl:apply-templates select="*" /> <!-- three nodes selected here -->

<xsl:template match="foo"> <!-- will be called once -->
  <xsl:text>foo element encountered</xsl:text>

<xsl:template match="*"> <!-- will be called twice -->
  <xsl:text>other element countered</xsl:text>

This way you give up a little control to the XSLT processor - not you decide where the program flow goes, but the processor does by finding the most appropriate match for the node it's currently processing.

If multiple templates can match a node, the one with the more specific match expression wins. If more than one matching template with the same specificity exist, the one declared last wins.

You can concentrate more on developing templates and need less time to do "plumbing". Your programs will become more powerful and modularized, less deeply nested and faster (as XSLT processors are optimized for template matching).

A concept to understand with XSLT is that of the "current node". With <xsl:apply-templates> the current node moves on with every iteration, whereas <xsl:call-template> does not change the current node. I.e. the . within a called template refers to the same node as the . in the calling template. This is not the case with apply-templates.

This is the basic difference. There are some other aspects of templates that affect their behavior: Their mode and priority, the fact that templates can have both a name and a match. It also has an impact whether the template has been imported (<xsl:import>) or not. These are advanced uses and you can deal with them when you get there.

Related Question