A named template is a segment of code which can be called from anywhere in the script by referring to its name. When this occurs, the script engine shifts its focus to the code within the selected template until the script completes. Then the script engine returns to the calling template and continues processing from where it left the script. 

Named templates can greatly enhance scripts in the following ways:
  • code re-use: if a particular code stanza has to be repeated multiple times throughout your script then it makes sense to place it within a named template instead. This reduces the size of your script and simplifies changes.
  • self-documentation: named templates with descriptive names clarify the script actions. A script that is written in this way is simpler to read and understand than one in which all the operations are performed in a single large main template.
  • recursion: a useful capability of named templates is their ability to call themselves. By looping through a section of code as many times as necessary, you can program the script to reach a specific end goal.

Named templates syntax
To create a named template you use the template statement, give it a name, and provide its curly brace enclosed code block:
template example-template {
/* Template code goes here */

To call a template use the call statement and include the name of the desired template:
call example-template;

In the example shown, the main template calls the display-user named template. The called template is then executed, causing the <output> element to be written to the result tree along with its included string. Although this is a simple example, it highlights a significant fact about named templates: any elements that are written to the result tree by a named template are inserted at the point the template is called. The main template code writes the <op-script-results> element to the result tree, but before doing so it calls the display-user template. The display-user template then provides the instructions to include the <output> element as a child element of <op-script-results>.

version 1.0;

ns junos = "http://xml.juniper.net/junos/*/junos";
ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";
ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

import "../import/junos.xsl";

match / {
    <op-script-results> {
        /* Call the display-user template */
        call display-user;

/* This template outputs the username to the console */
template display-user {
    <output> "Your user name is " _ $user;