Wikipedia:TemplateData/Tutorial

From Wikipedia, the free encyclopedia
Jump to: navigation, search

TemplateData is a way of storing information about a template—such as parameter names, or a description of the template—so that the VisualEditor can retrieve it and populate the template editor with it. It does not change anything about the actual template with which it appears, and nothing you can do with TemplateData will affect the functionality of or "break" any existing Wikipedia template (though mistakes that appear in the TemplateData might cause editors to use the associated template or its parameters incorrectly, so care is still needed). TemplateData is controlled by MediaWiki's TemplateData extension, which allows users to write small bits of structured data to a template page, or to be transcluded into that template page (such as on the standard documentation page). Once a template has this structured data, it can be displayed properly in the VisualEditor. While this may sound complex, it's actually very easy.

How to use TemplateData[edit]

The structure of TemplateData[edit]

TemplateData's structure is based around the "JSON" standard, and is fairly simple. The first thing to do is to type out a pair of <TemplateData> tags directly on the template page itself inside tags, or anywhere on the template's documentation sub-page if it has one, like so:

<TemplateData>
TemplateData goes here
</TemplateData>

N.B. The preceding will throw a JSON error if used alone; see #Completing the TemplateData information below for more information.

This tells the software that everything between the two tags is TemplateData, and should be referenced when the template is used. The TemplateData itself follows a standard layout that identifies the parameters that may be set within the template.

TemplateData[edit]

The TemplateData is added to the template page itself inside tags, or anywhere on the template's documentation page if it has one. In some cases, the main template page will be locked to prevent editing by unauthorized users. In that situation, the TemplateData can only be added to the /doc page; the link to that page is at the bottom of the main page.

The TemplateData is generally placed after the descriptive information about the template, and before the "See also" section.

Note: You should add {{TemplateDataHeader}} directly in front of the <templatedata> tag. This will categorize the page as TemplateData documentation and allow later organization of templates and their documentations.

Identifying the parameters[edit]

If the template has no parameters, you can complete its TemplateData block with a simple line of "params": {}. If you do not include this line, you will not be able to save the page. This completes the TemplateData for the template.

However, most templates have parameters, such as dates, URLs, article names, images, numbers or strings. Determine which parameters are or may be used in the template. Parameters may be passed by equal signs. For instance, the {{cite web}} template is passed values to complete a citation, such as url=, title=, accessdate=, etc. Other parameters may be used by their position instead. In this case, use numbers "1", "2", etc. instead of names for the parameters. The template documentation on the main or sub-page may summarize which parameters can be set on a template, and what each parameter must include.

Completing the TemplateData information[edit]

Remember, TemplateData information is only information about how a template is meant to be used by editors. Nothing you do here will affect the corresponding template, though creating a TemplataData entry that contains informational errors may cause problems for editors trying to use that template in an article.

The first piece of information to fill out is a "description" for the overall template, which is fairly self-explanatory; it briefly describes what the template does and explains where and how the user might want to use it. If the template was created and given some kind of description by someone before you, you may use information that you glean from the top of the main or sub-page of the template, which you can copy and paste here. Place it within quotes and follow it with a comma: "description": "This template generates an information box for Croatian football players",). Note that any wikitext typed anywhere in the TemplateData table such as [[Croatian football]] will not retain any of its functions and will appear as plain unlinked text, character for character.

Next, you should create a "params" block, with braces ({ and }). Inside this block, you need to create a sub-block for each parameter used by the template, with some of the following entries. Most of it is optional, but the more information you give the easier it will be for others to re-use the template.

  • Create or use the short arbitrary "name" for the parameter that will be read by the Wikipedia template software. If you use or the template has a parameter name containing more than one word, these must always be separated by an underscore: _ like this: ocean_size (i.e., parameter names do not contain spaces). Place it between double quotes, follow it with a colon, and create a block with some more single braces { and } like this: "ocean_size": { } or "range_map": { }. Note that many templates like {{Infobox Fabergé egg}} have a variable which is itself called "name", and therefore the JSON code for this parameter would be written "name": { }. The following code now goes within these braces, separated by a comma at the end of each but none after the last, and with no additional braces (Note that the order of these entries is irrelevant: they will be ordered in a consistent pattern when the JSON TemplateData code is read):
    • The "label" entry is a human-readable title for the parameter that will be displayed within the template editor. Capitalize the first character of the label (since it will be the leftmost value in the resulting table), and put it in quotes, like this: "Ocean size":.
    • Enter the parameter's "description" (i.e., a description of the specific parameter, not the template as a whole). This may already have been written on the template's main or documentation page, and can be copied and pasted into place. Put this information in quotes. If you wish your description to also display a word or phrase in quotes, you must put a forward slash / directly before the quote mark like this: "This parameter indicates the /"size/" of the ocean". If you do not provide the forward slash directly before the quote mark, the JSON software will interpret the mark as the end of the parameter block— the forward slash tells JSON, "Don't count the quote mark directly following me— render it as a visible quote mark and look for the end-of-parameter quote mark further on". If the word you wish to display in quotes is at the very end of your parameter description, you will just need to type /"" like this: "This parameter indicate the ocean /"size/"" You may include any other punctuation (comma, semicolon, colon, brace, bracket, double bracket, etc.) between the two double-quote marks as you like.
    • You can optionally set a flag on the status of the parameter:
      • "required" says that filling out the parameter is mandatory for that template. Only set this to true if the value is required for the template, and not setting a value will break the template (like the URL for Cite web). Entries for this flag must be either the word true or false, with no quotation marks.
      • "suggested" says this is one variable that most users of the template will probably want to fill in (like the source date for a citation). You should almost always have at least one suggested parameter on a template. Like required, use either the word true or false, with no quotation marks.
      • "deprecated" can be set to flag whether or not this parameter is in regular use – as well as setting to true, you can write a brief description about what users should do instead. Rare.
    • The "aliases" group lets you list other names for this parameter which have been set to work equally well, and its entry is enclosed by a single bracket, i.e., "aliases": [ "2", "Caption", "imagecaption" ]. An alias is an alternative name for the parameter that the template is willing to accept instead of (not in addition to) the primary name. Aliases are not documented in a separate parameter object.
  • The "autovalue" entry lets you tell VisualEditor and other tools to pre-fill this parameter with a standard value (in wikitext); this text will show up in the parameter box when users edit, and will be added to the template invocation when saved. This may be useful for cleanup templates to automatically set the date the user adds a template. For example, add ""autovalue": "{{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}" as the autovalue to have the relevant date, "June 2017" automatically added when an editor uses the template(example edit). Autovalues may be changed by the editor simply by removing the supplied value in the template dialog. Note that this subst-based method does not work for any templates that are used inside <ref> tags, gallery tags, or other extension-specific tags. Whether or not set by the person creating the TemplateData code, this entry, whatever it is, will appear as an entry in the resulting TemplateData table; if not created manually, it will be followed by the word "Empty".
  • The "default" setting lets you show what the template will do if this parameter isn't set (or is set but left blank); this text will show up as light gray text in the parameter box when users edit, but will not add the value to the template invocation when saved unless the user manually overrides it. Rare. This entry will always appear in the resulting TemplateData table, and if not manually created by the person writing the TemplataData code, will be followed by the word "Empty".
  • The "example" entry allows you to display an example of an entry that a person might make for this variable, written exactly as a person might type it, character-for-character; if the type of entry has already been set with the "type" parameter (see below), then the example should reflect this (i.e., if the type has been set to "wiki-page-name" then your example should not include a prefix like "File:" or "Image:"). Be sure to enclose the entire text of the example with quotes. Obviously, this means the actual example may not contain quote marks itself. If not created by the person writing the TemplataData code, will be followed by the word "Empty".
  • The "type", which controls how the template editor will interpret that parameter. This can be one of a few values, any of which used must be enclosed in double-quote marks:

String Value

Type of Parameter

"unknown" Assumed type if not set
"number" Any numerical value (without decimal points or thousand separators)
"string" Any textual value
"line" Short text field - use for names, labels, and other short-form fields
"wiki-page-name" A valid MediaWiki page name for the current wiki. Doesn't have to exist, but if not, should be a valid page name which could be created.
"wiki-file-name" A valid MediaWiki file name for the current wiki. Doesn't have to exist, but if not, should be a valid file name which could be uploaded. Should not include the namespace (e.g. "Foo.svg" not "File:Foo.svg" or "Bild:Foo.svg").
"wiki-user-name" A valid MediaWiki user name for the current wiki. Doesn't have to exist, but if not, should be a valid user name which could be created. Should not include the namespace (e.g. "Foo" not "User:Foo" or "Usario:Foo").
"content" Page content in wikitext, such as text style, links, images, etc.
"unbalanced-wikitext" Raw wikitext that should not be treated as standalone content because it is unbalanced - for example, templates concatenating incomplete wikitext as a bigger whole, such as{{echo|before=<u>|after=</u>}}
"date" A date in ISO 8601 format, e.g. "2014-05-09" or "2014-05-09T16:01:12Z"
  • "inherits". This is a key to another parameter. The current parameter will inherit from that one, with local properties overriding the inherited ones. Very rare. Currently, the inclusion of this parameter in a templatedata sub-block will cause the page to produce a Required property "params." not found. error and will fail to generate the expected table.

Where more than one parameter sub-blocks is passed to the template, you must add a comma after the close brace, },, between the sub-blocks. Do not place a comma after the last sub-block in your set, but do make sure that there is a final close brace, }.

A further option "format" determines how the wikitext code for the template will be formatted when it is saved by the VisualEditor. This can have the options "format": "inline" (the default) or "format": "block". With the inline option the wikitext of the template will be formatted as single line {{Sister project|project = commons|text = page in commons}} with the block option each parameter will take a single line

{{Infobox television
| show_name = Father Ted
| genre = Comedy
}}

This option may be preferable for very complex templates like infoboxes which have multiple parameters. The documentation page indicated the format with the line "This template prefers inline formatting of parameters." or "This template prefers block formatting of parameters."

Save[edit]

Once you're done, hit "save". If you've made errors, it will not let you save – which can be a little frustrating, as the resulting error message will not tell you where JSON encountered the first code error, but means you can't "break" anything or put up a table that is accidentally malformed. If you find you are unable to save because of a code error, some common problems to look for include:

  • Is every opening quote (") matched with a closing quote in the correct place of the code?
  • Does a string, such as a description of a parameter, contain a " that is not at the end of the entry? If so, consider replacing it with a '.
  • Is every opening brace({) matched with a closing brace(}) in the correct place?
  • Are there commas between params blocks? (There should be one).

Manually searching through the program for these errors can be tiresome and difficult. Fortunately, a number of program checking websites for JSON exist which will at least identify the line on which the program first encounters an error. [1] is one of these which seems to work quite well. Simply copy and paste the problematic JSON code into the corresponding box on the website and ask it to check the code— it will not itemize every error in the document, but it will indicate the first error it encounters, if any, which should be immensely helpful in correcting your code.

Once you successfully save the page, it may take a few minutes after saving for the TemplateData to be integrated into VisualEditor. If it doesn't come through after a few minutes, you can make a null edit on the main template to fix this. As many templates are protected, you may need to request a null edit using {{editprotected}} or leaving a note on Wikipedia talk:VisualEditor/TemplateData tutorial.

Worked example[edit]

The {{Str left}} template is a simple template used like {{Str left|<string>|<count>}} to show the first few characters of an input. It has two parameters, neither of which are named (they are only recognised by their position in the template), and both of which are required. Thus the TemplateData for this template might be:

<templatedata>
{
	"description": "Give the first few characters from the start of the input",
	"params": {
		"1": {
			"label": "Input",
			"description": "The string to be trimmed and counted",
			"required": true,
			"type": "string"
		},
		"2": {
			"label": "Length",
			"description": "How many characters of the input should be returned",
			"required": true,
			"type": "number"
		}
	}
}
</templatedata>

… which would display in the template like so:

Give the first few characters from the start of the input

Template parameters

Parameter Description Type Status
Input 1

The string to be trimmed and counted

Default
empty
Example
empty
Auto value
empty
String required
Length 2

How many characters of the input should be returned

Default
empty
Example
empty
Auto value
empty
Number required

Complete empty TemplateData block[edit]

You can just copy and paste this to use when creating your own.

<templatedata>
{
	"description": "zzzzz",
	"params": {
		"first parameter": {
			"label": "x",
			"description": "xxx",
			"required": false,
			"suggested": false,
			"example":"x",
			"deprecated": false,
			"aliases": [],
			"autovalue": "auto value",
			"default": "default value",
			"type": "string"
		},
		"second parameter": {
			"label": "y",
			"description": "yyy",
			"required": false,
			"suggested": false,
			"example": "x",
			"deprecated": false,
			"aliases": [],
			"autovalue": "auto value",
			"default": "default value",
			"type": "number"
		}
	},
    "sets": { }
}
</templatedata>

Shared documentation[edit]

Many templates share the same documentation. For example {{multicol}}, {{multicol-break}} and {{multicol-end}} all use Template:Multicol/doc. If the TemplateData is included in the documentation page then this will cause some of the templates to pick up the wrong template data section.

This can be resolved by putting the TemplateData in an individual sub page, {{col-begin}} uses Template:Col-begin/TemplateData or in the template page itself as in {{top}}. An alternative technique is to use {{#switch: {{PAGENAME}} | ...}} in the document page with the different templatedata sections in each switch block. Template:Multicol/doc is an example of this. This has the advantage that the documentation page is generally not protected so all editors can update the documentation.

Help[edit]

Should you run into errors, explain on the feedback page what you were trying to do, and we'll be happy to help.

Examples[edit]

A template which takes no parameters: {{fixed}}. Note the params must be give as an empty list.

Markup Renders as
<templatedata>{
  "description": "Displays a tick mark and the word fixed. It takes no parameters.",
  "params": { }
}</templatedata>

Displays a tick mark and the word fixed. It takes no parameters.

Template parameters

Parameter Description Type Status
No parameters specified

A template with aliases {{quote}}:

Markup Renders as
<templatedata>{
  "description": "Adds a block quotation.",
  "params": {
    "text": {
      "label": "text",
      "description": "The text to quote",
      "type": "string",
      "required": false,
      "aliases": [ "1", "quote" ]
    },
    "sign": {
      "label": "sign",
      "description": "The person who quote it is",
      "type": "string",
      "required": false,
      "aliases": [ "2", "cite" ]
    },
    "source": {
      "label": "source",
      "description": "A source for the quote",
      "type": "string",
      "required": false,
      "aliases": [ "3" ]
    }
  }
}</templatedata>

Adds a block quotation.

Template parameters

Parameter Description Type Status
text text1quote

The text to quote

Default
empty
Example
empty
Auto value
empty
String optional
sign sign2cite

The person who quote it is

Default
empty
Example
empty
Auto value
empty
String optional
source source3

A source for the quote

Default
empty
Example
empty
Auto value
empty
String optional

A template with default values {{col-6}}. Note default values are the values used by a template when the parameter is not specified. This example uses the "format": "block" option.

Markup Renders as
<templatedata>
{
    "description": "Starts a new column, for use with {{col-begin}} when there are six columns.",
    "params": {
        "width": {
            "label": "width",
            "description": "Width of the column.",
            "type": "string",
            "default": "16.66%",
            "aliases": ["w"],
            "required": false
        },
        "align": {
            "label": "align",
            "description": "Horizontal alignment.",
            "type": "string",
            "default": "left",
            "required": false
        },
        "valign": {
            "label": "valign",
            "description": "Vertical alignment.",
            "default": "top",
            "type": "string",
            "required": false
        }
    },
    "format": "block"
}
</templatedata>

Starts a new column, for use with {{col-begin}} when there are six columns.

Template parameters

This template has custom formatting.

Parameter Description Type Status
width widthw

Width of the column.

Default
16.66%
Example
empty
Auto value
empty
String optional
align align

Horizontal alignment.

Default
left
Example
empty
Auto value
empty
String optional
valign valign

Vertical alignment.

Default
top
Example
empty
Auto value
empty
String optional

Limitations and questions[edit]

TemplateData is great for editing existing templates, but does not currently automatically pull in parameters when you create a new template. The ability to have it do that is being worked on now. There is some delay between the implementation and it showing up in existing templates - which makes debugging slightly difficult. There is also a slight delay after TemplateData is created before it appears in the VisualEditor.

Template data was previously limited to 65,535 bytes (bug 51740http://bugzilla.wikimedia.org/show_bug.cgi?id=51740). This limit could be exceeded for some templates which use many parameters, such as {{Infobox officeholder}}, but the code is now compressed, increasing the limit.

Tools[edit]

Editor for TemplateData

External links[edit]

  • Jsonlint a JSON validator to help spot errors in the template data syntax.