Jump to content

Extended template syntax/Alternative conditional syntax proposal

From Meta, a Wikimedia project coordination wiki

This is a proposal to extend the template wikicode syntax with a powerful conditional construct, similar to the if/then/else and switch/case constructs found in other computer languages. It supplements the "if defined" and "for each" constructs proposed in Extended template syntax.

The syntax of a conditional would be {{{if:parameter|options}}} where "if:" is the pseudo-namespace for the conditional, parameter is the template parameter to be compared, and options is one or more pairs of comparison and text to be inserted. The syntax of an option is {condition|inserted text} where condition is one of a set of tests that can be applied to parameter, and inserted text is wikitext to be transcluded if the test is true.

The possible conditions are:

is:value
The text is inserted if the value of parameter is equal to value.
contains:substring
The text is inserted if the value of parameter contains the substring substring. If parameter is a multi-value parameter, the text is inserted if any of the subparameters contain substring.
does not contain:substring
The text is inserted if substring is not in parameter.
in:set
The text is inserted if the value of parameter matches one in set. Set is a cmma-separated list of one or more values or ranges. Ranges are of the form range start--range end, and may be of any type MediaWiki knows how to order (numbers, dates).
undefined
The text is inserted if parameter is undefined (that is, the argument was not provided in the template call). This is the opposite of the "if defined" construct.
else
The text is inserted if parameter doesn't match any preceding condition. This "test" always succeeds if it is reached.

A single if construct may contain several options, which parameter is tested against in order until one succeeds. It therefore behaves more like a switch/case statement than a traditional if/then statement, but the term "if" was chosen because it is more readable to English-speaking nonprogrammers.

An example of an if construct in action:

{{{if:color| {in:red,fuschia,crimson,scarlet|red} {is:blue|blue} {contains:green|green} {undefined|} {else|technicolor} }}}

A template containing this conditional would insert "red" if the color parameter was given as one of a few types of red; "blue" if it was exactly equal to "blue"; "green" if color was "green", "bluegreen" or any other string containing the substring "green"; nothing if the color argument wasn't given; and "technicolor" if the value of color was something unexpected.