Help us improve your experience.

Let us know what you think.

Do you have time for a two-minute survey?


SLAX Functions Overview

Version 1.1 of the SLAX language, which is supported in Junos OS Release 12.2 and later releases, supports functions. When the complexity of a script increases or a code segment appears in multiple places, you can modularize the code and create functions. Functions accept arguments and run only when explicitly called.


Version 1.2 of the SLAX language, which is supported in Junos OS Release 14.2 and later releases, supports SLAX elements as arguments to both templates and functions.

Functions have several advantages over templates, including the following:

  • Arguments are passed by position rather than name.

  • Return values can be objects as opposed to result tree fragments.

  • Functions can be used in expressions.

  • Functions can be resolved dynamically (using EXSLT dyn:evaluate()).

In SLAX, you define a function definition as a top-level statement in the script. The function definition consists of the function keyword, the function name, a set of arguments, and a braces-delimited block of code. The function name must be a qualified name. The argument list is a comma-separated list of parameter names, which are positionally assigned based on the function call. Trailing arguments can have default values. Alternatively, you can define function parameters inside the function block using the param statement. The syntax is:

The return value can be a scalar value, an XML element or XPath expression, or a set of instructions that emit the value to be returned.

If there are fewer arguments in the function invocation than in the definition, the default values are used for any trailing arguments. If there are more arguments in the function invocation than in the definition, the function call generates an error.

The following example defines the function size, which has three parameters: width, height, and scale. The default value for scale is 1. If the function call argument list does not include the scale argument, the calculation uses the default value of 1 for that argument. The function’s return value is the product of the width, height, and scale variables enclosed in a <size> element.

In the main match template, the function call uses width and height data selected from each graphic/dimension element in the source XML file. The script evaluates the function, and the copy-of statement emits the return value to the result tree as the contents of the <out> element.

The following function definition uses param statements to define the parameters instead of a comma-separated list. The behavior of the function is identical to that in the previous example.