Lua templating/Converting Wikitext templates

Collected here are tips for converting Wikitext templates to Lua.

Switch statements
One of the most common cases of a slow template is due to a large  statement, which are often called multiple times on the same page. By making use of  and a simple table of data, we can make these templates significantly faster. By using a simple Lua table of data, we move to using a roughly O(1) hash table lookup, and by using, the data will only be loaded once in a page load no matter how many times Module:FooBar is invoked on a page. For a switch statement with 150 items, converting it to Lua in this way resulted in an approximately 50% improvement in parse time.

For example, if you have a template that uses a switch statement like so:

To convert it to Lua, create two module pages.

Module:FooBar:

Module:FooBar/data:

Conditional  statements (#if)
Many templates make use of "#if" parser functions resulting in a lot of nested functions, which may make the code very complex and hard to understand. This can be converted and made more efficient using Lua. See live demo.

For example, to create template that checks if a template argument contains "text", one would write something like:

This can be converted to: Module:if :

This can be applied to complex "#if" based parser functions, and would be much easier to understand.

Check if article exists (#ifexists)
Create Module:ifexists :

Then simply use.

Note: This sadly still remains an expensive function.

Loop Statements (#for)
One way to reduce the template size, and to make it load faster and more efficiently is to reduce repeated text. This can typically be achieved by using loops or using Lua.

A template that repeats some text can be created using the loops extension by writing:

Calling template foo : {{ foo: |n=4 | list1=a | list2=b | list3=c | list4=d } Which contains the following text:

Will result in the text:

a♣b♣c♣d♣

This can be converted to Module:loop:

Template:foo : {{#invoke:loop|appendloop}

Calling template foo with these arguments: {{foo|a|b|c|d}

Results in : a♣b♣c♣d♣

Time function (#time)
Time functions can be converted with the following module:time :

This can then be called using :

This shows the date, e.g. 2013-10-04. The special characters used to get these date can be found in the lua's page.