apply-templates vs call-template: What Is the Difference?

In Extensible Stylesheet Language Transformations (XSLT), both <xsl:apply-templates> and <xsl:call-template> are used to invoke templates, but they operate on fundamentally different execution models. The primary difference is that <xsl:apply-templates> uses declarative pattern matching to process nodes dynamically based on the input XML structure, whereas <xsl:call-template> operates imperatively, executing a specific named template directly like a traditional subroutine or function. Understanding how each manages context, rules, and document flow is critical for writing maintainable, idiomatic XSLT stylesheets.

Understanding <xsl:apply-templates>

The <xsl:apply-templates> instruction tells the XSLT processor to select a set of nodes and find the best-matching template rule defined with a match attribute.

Key characteristics include:

Example:

<!-- Invocation -->
<xsl:apply-templates select="book/chapter" />

<!-- Template Definition -->
<xsl:template match="chapter">
  <section>
    <xsl:apply-templates select="title | paragraph" />
  </section>
</xsl:template>

Understanding <xsl:call-template>

The <xsl:call-template> instruction directly invokes a template identified by its name attribute, bypassing pattern matching entirely.

Key characteristics include:

Example:

<!-- Invocation -->
<xsl:call-template name="render-header">
  <xsl:with-param name="title" select="'Summary Report'" />
</xsl:call-template>

<!-- Template Definition -->
<xsl:template name="render-header">
  <xsl:param name="title" />
  <header>
    <h1><xsl:value-of select="$title" /></h1>
  </header>
</xsl:template>

Side-by-Side Comparison

Feature <xsl:apply-templates> <xsl:call-template>
Programming Paradigm Declarative / Rule-based Imperative / Procedural
Target Resolution Resolved dynamically via match attribute Resolved explicitly via name attribute
Context Node Changes to the node being processed Stays the same as the calling instruction
Node Set Iteration Iterates over selected node sets automatically Does not iterate; executes once per call
Coupling Loosely coupled with input XML structure Tightly coupled with the target template name
Support for Modes Supported (mode="...") Not supported

When to Use Which Directive

Use <xsl:apply-templates> when transforming document hierarchies, reordering or filtering elements, and leveraging recursive descent through arbitrary XML trees. It enables modular stylesheets that can adapt to structural variations without rewriting control flow.

Use <xsl:call-template> when creating isolated helper functions, performing recursive mathematical or string-processing calculations, or generating fixed structural components that do not depend on matching specific XML input nodes.