Extension:VariablesExtension

Variables is a very simple mediawiki extension which allows you to define a variable on a page, use it later in that same page, change its value, possibly to a value given by an expression in terms of the old value, etc.

It's much like a template only very lightweight and scoped to only a single page, so you can use many variables on a page without polluting the wiki with huge numbers of templates. Combine with the ParserFunctions extension for best results.

This dead simple extension was written by Rob Adams, and he has released it into the public domain. It was ported to version MediaWiki version 1.8 by Hempel.

Assigning a value to a variable


assigns the value value to the (already existing or hereby introduced) variable variablename.

Retrieving the value of a variable
The value of the variable variablename is produced by

If undefined this produces the empty string, it does not give an error message.

The value can be used in parser functions, etc.

Examples
Compute 2*a + b:

Add one to n:

Variables and conditional parser functions
It must be noted that everything in conditional parser functions such as #ifexpr gets executed (though only one result gets displayed), regardless of the condition, see ParserFunctions. This applies also to #vardefine. Thus:

first assigns b and then c (hence effectively just c) regardless of the condition, while

assigns only the applicable value.

Similarly

assigns b regardless of the condition, while

conditionally assigns value b to variable a (a dummy assignment of the value of a to a is done if the condition is not fulfilled).

Installing
Copy this into a file called $mediwikipath/extensions/Variables/Variables.php:

 'VariablesExtension',                                             'url' => 'http://meta.wikimedia.org/wiki/VariablesExtension',                                              'author' => 'Rob Adams' );

$wgExtensionFunctions[] = 'wfSetupVariables'; $wgHooks['LanguageGetMagic'][] = 'wfVariablesLanguageGetMagic';

class ExtVariables { var $mVariables;

function vardefine( &$parser, $expr = , $value =  ) { $this->mVariables[$expr] = $value; return ''; }

function varf( &$parser, $expr = '' ) { return $this->mVariables[$expr]; } }

function wfSetupVariables { global $wgParser, $wgExtVariables;

$wgExtVariables = new ExtVariables;

$wgParser->setFunctionHook( 'vardefine', array( &$wgExtVariables, 'vardefine' ) ); $wgParser->setFunctionHook( 'var', array( &$wgExtVariables, 'varf' ) ); }

function wfVariablesLanguageGetMagic( &$magicWords, $langCode ) { switch ( $langCode ) { default: $magicWords['vardefine'] = array( 0, 'vardefine' ); $magicWords['var'] = array( 0, 'var' ); }	return true; }

?>

Then add require_once( "$IP/extensions/Variables/Variables.php" ); to the end of LocalSettings.php.