To enable TemplateScripts in your wiki, add the following code to MediaWiki:Common.js (and MediaWiki:Mobile.js):
With this code, any HTML tag (for example a <div> or <span>) with the attribute
The code is quite simple so you can easily adapt it to the needs of your community. However, the restriction to the MediaWiki namespace is essential to prevent security risks, and the restriction to the "TemplateScript-" prefix is important to prevent this code from loading other scripts in the MediaWiki namespace that could cause trouble. Finally, the check to prevent the same script from loading more than once is important because otherwise some template scripts may load dozens or even hundreds of times per page, causing unnecessary load on the server.
Available template scripts
- Form - Create forms that inject content into other pages (see it live)
- Sign - Easily sign in votes, polls and wikiprojects (see it live)
- Search - Show search results in pages (see it live)
- Vivarium - Create an interactive version of Conway's Game of Life (see it live)
- Formicarium - Create an interactive version of Langton's ant (see it live)
- ExcerptTree - See and navigate excerpt trees (see it live)
- Wikidebate - Tools for wikidebates (see it live)
- Add HTML elements that templates normally don't permit, like
- Add HTML attributes that templates normally don't permit, like
- Call the Wikipedia API using the friendly mw.Api library (example)
- Modify HTML and CSS in advanced and dynamic ways, for example using jQuery
- Use data attributes to pass data to the script and do complex processing or advanced behavior switches (example)
Good script design guidelines
- You can design your script for your wiki only, but you can also try to generalize it to be usable by other wikis (example). If you do so, consider hosting it at a central wiki like MediaWiki.org or Commons (example) and have other wikis load it from there (example). If you don't, then versioning can be useful to keep track of which version is being used in each wiki (example).
- Separation of concerns can be achieved by moving HTML to the template (example) and CSS to a separate stylesheet (example) that can then be loaded via TemplateStyles or from the template script (example).
- One template may load several template scripts, and one template script may load other template scripts too, so consider writing modular and reusable scripts. However, don't abuse dependencies since each one fires an additional web request.
- Encapsulate your code within a class to keep it tidy and avoid unnecessary naming conflicts (example).
- phab:T131436 - Experimental interface for embedding with partial security isolation. With further development, this will probably merge with TemplateScripts to provide infrastructure for scripts that are easier to review for security.