Template variables provide a convenient way of storing and retrieving data within a template. This section explains how variables are defined and referenced.
Variable definitions take the basic form:
$<name> = <value>
where <name> can be any alpha-numeric sequence and <value> is derived from a macro or another variable.
A simple example definition would be:
$foo = %className%
Variables can be defined using values from:
- Substitution, function or list macros
- String literals, enclosed within double quotation marks
- Variable references
These rules apply to variable definitions:
- Variables have global scope within the template in which they are defined and are not accessible to other templates
- Each variable must be defined at the start of a line, without any intervening white space
- Variables are denoted by prefixing the name with $, as in $foo
- Variables do not have to be declared, prior to being defined
- Variables must be defined using either the assignment operator (=), or the addition-assignment operator (+=)
- Multiple terms can be combined in a single definition using the addition operator (+)
Using a substitution macro:
$foo = %opTag:"bar"%
Using a literal string:
$foo = "bar"
Using another variable:
$foo = $bar
Using a list macro:
$ops = %list="Operation" @separator="\n\n" @indent="\t"%
Using the addition-assignment operator (+=):
$body += %list="Operation" @separator="\n\n" @indent="\t"%
That definition is equivalent to:
$body = $body + %list="Operation" @separator="\n\n" @indent="\t"%
Using multiple terms:
$templateArgs = %list="ClassParameter" @separator=", "%
$template ="template<" + $templateArgs + ">"
Variable values can be retrieved by using a reference of the form:
where <name> can be a previously defined variable.
Variable references can be used:
- As part of a macro, such as the argument to a function macro
- As a term in a variable definition
- As a direct substitution of the variable value into the output
It is legal to reference a variable before it is defined. In this case, the variable is assumed to contain an empty string value: ""
Variable References - Example 1
Using variables as part of a macro. This is an excerpt from the default C++ ClassNotes template.
$wrapLen = %genOptWrapComment%
$style = %genOptCPPCommentStyle% (Define variables to store the style and wrap length options)
%if $style == "XML.NET"% (Reference to $style as part of a condition)
%CSTYLE_COMMENT($wrapLen)% (Reference to $wrapLen as an argument to function macro)
Variable References - Example 2
Using variable references as part of a variable definitions.
$foo = "foo" (Define our variables)
$bar = "bar"
$foobar = $foo + $bar ($foobar now contains the value foobar)
Variable References - Example 3
Substituting variable values into the output.
$bases=%classInherits% (Store the result of the ClassInherits template in $bases)
Class %className%$bases (Now output the value of $bases after the Class name)