Template:Var/doc
The Var template is used to store data in the cache for later use.
Usage
{{Var|name|data}}
Name
The name of the variable. Case sensitive.
Data
The data to be stored in the variable. The literal value is stored and is not evaluated (unless you also store the appropriate functions) - if you store 6*7, when you recall it you will get the result 6*7
, not 42; if you store {{#expr:6*7}}
you will get the result 42
.
Recalling data
Recalling data is done by use of the #var parser function:
{{#var:name}}
where name is the same named used in the var template above.
Expansion on usage
Variables can be redefined where needed - you can use the Var template many times.
Variables can be called where needed - you can use the #var parser function many times.
Variables can be defined recursively, that is defined as a function as themselves. For example:
{{Var|i|0}} {{Var|i|{{#expr:{{#var:i}}+1}}}}
The first line initialises the variable i to 0 (required to prevent expression errors), and the second will increment i by one each time it is used. If you place the second line into a template that is used multiple times on a page e.g. a table row template, you can recall i to find something that may be of importance in context e.g. the number of rows in the template. As an additional note, the increment doesn't have to be 1, it can be any number - it doesn't even have to be a fixed number, it can be a function of some other parameters in the template.
Rationale
"But I know how to use the #vardefine parser function. Isn't this the exact same thing?"
Yes, it is. The Var templates uses the #vardefine parser function to define the variables. So what's the point of this template?
A problem with the design of the variables extension is that vardefine is always executed even if it is on the false path of a conditional parser function: for example, if you created a construct such as
{{#ifexpr: ... |{{#vardefine:a|b}} |{{#vardefine:a|c}} }}
Variable a will now always hold c, regardless of whether the expression is true or false.
There are two ways around this. The first is to move the #vardefine to the outside of the conditional parser: following the previous example, the required construct would be similar to
{{#vardefine:a|{{#ifexpr: ... |b|c}}}}
However, sometimes you can't move the #vardefine outside, it logically makes more sense or is easier to follow to leave the #vardefine on the inside. This is where the Var template comes in. As the template is not expanded if it is on the false path, the #vardefine is not present and cannot define variables where it shouldn't. Thus a construct like this will also work for the above example:
{{#ifexpr: ... |{{Var|a|b}} |{{Var|a|c}} }}
See also
The Variables Extension page on MediaWiki