Jump to content

英文维基 | 中文维基 | 日文维基 | 草榴社区

Wikipedia:TemplateData/Tutorial

From Wikipedia, the free encyclopedia

Template data 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 template data will affect the functionality of or "break" any existing Wikipedia template (though mistakes that appear in the template data might cause editors to use the associated template or its parameters incorrectly, so care is still needed). Template data 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 template data

[edit]

The structure of template data

[edit]

Template data's central structure is encoded in JSON format, and the schema is fairly simple. The first thing to do is to type out a pair of <templatedata> tags directly on the template page itself inside <noinclude>...</noinclude> 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 is incorrect code if used as it is and will therefore throw a JSON error if used; see #Completing the template data information below for more information.

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

On English Wikipedia, you can also use the {{Format TemplateData}} template to generate a more "conventional" presentation of template data suitable for use in Template documentation. Instead of the above, write this at the top of the documentation page:

{{Format TemplateData
|1=<templatedata>
TemplateData goes here
</templatedata>
|TOC=1
}}

Template data

[edit]

The template data is added to the template page itself inside <noinclude></noinclude> 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 template data can only be added to the /doc page; the link to that page is at the bottom of the main page.

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

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

Identifying the parameters

[edit]

If the template has no parameters, you can complete its template data 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 template data 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=, access-date=, 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. Also, template data must be included in the template documentation page.

Completing the template data information

[edit]

Remember, template data information is both information about how a template is meant to be used by editors, and programming code that tells the VisualEditor how to help editors add a template to a page. Nothing you do here will affect the corresponding template, though creating a template data entry that contains 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 template data 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 template data 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 escape the quotation marks by putting a backslash \ directly before them like this: "This parameter indicates the \"size\" of the ocean". If you do not provide the backslash directly before the quotation mark, the JSON software will interpret the mark as the end of the parameter block— the backslash tells JSON, "Don't count the quotation mark directly following me— render it as a visible quotation mark and look for the end-of-parameter quotation 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 indicates the ocean \"size\"" You may include any other punctuation (comma, semicolon, colon, brace, bracket, double bracket, etc.) between the two quotation marks as you like. Note, however, that should you need an actual backslash \ as part of the text, you will have to escape that too with another backslash, like this: \\.
    • 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, "November 2024" 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 template data code, this entry, whatever it is, will appear as an entry in the resulting template data 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 is not 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 template data table, and if not manually created by the person writing the template data 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 quotation marks itself. If not created by the person writing the template data 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 quotation 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. May contain line breaks.
"line" Short text field – use for names, labels, and other short-form fields. This is supposed to be text that is not expected to contain line breaks.
"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"
  • The "suggestedvalues" parameter property lets you define a list of parameter values to be shown to VisualEditor users for easy selection. Once the values have been added to TemplateData, the VisualEditor will display them in a combo box (a dropdown into which users can also enter a custom value). The user selects the desired value by clicking on it. For the suggested values to be displayed in the VisualEditor, the parameter’s type must be one of the following: content, line, string, number, unknown or unbalanced wikitext. Adding this parameter property can be done either in JSON or using the TemplateData Editor with no coding required. Both methods are explained here.
  • "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. The primary options are "format": "inline" (the default) and "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}} and with the block option, each parameter will be placed on a new line

{{Infobox television
| 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."

For more complex parameter formatting options, see mw:Help:TemplateData#Custom_formats.

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 cannot "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 template data 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 template data 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

ParameterDescriptionTypeStatus
Input1

The string to be trimmed and counted

Stringrequired
Length2

How many characters of the input should be returned

Numberrequired

Note: As explained above, the TemplateData block does not affect how the template works, but it does affect editors' use of the template in the VisualEditor. In the {{Str left}} example above, parameter |2= is listed as "required", which means that the VisualEditor will require entry of a value, even though the template's actual code does not require parameter |2= to be present in transclusions of the template. This difference can be confusing to editors.

Complete empty template data 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. Putting template data on a subpage has the advantage that the documentation page is generally not protected so all editors can update the documentation. However, if the template data is included in a shared 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 template data in an individual subpage (Template:col-begin/doc uses Template:Col-begin/TemplateData) or in the template page itself (as in {{collapse top}}). An alternative technique is to use {{#switch: {{PAGENAME}} | ...}} in the document page with the different <templatedata> sections in each switch block.

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 given 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

ParameterDescriptionTypeStatus
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

ParameterDescriptionTypeStatus
texttext 1 quote

The text to quote

Stringoptional
signsign 2 cite

The person who quote it is

Stringoptional
sourcesource 3

A source for the quote

Stringoptional

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 prefers block formatting of parameters.

ParameterDescriptionTypeStatus
widthwidth w

Width of the column.

Default
16.66%
Stringoptional
alignalign

Horizontal alignment.

Default
left
Stringoptional
valignvalign

Vertical alignment.

Default
top
Stringoptional

Limitations and questions

[edit]

Template data 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 template data is created before it appears in the VisualEditor.

Template data was previously limited to 65,535 bytes (Phabricator: T53740). 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 template data

==

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