使用方法/TemplateData

来自康健生活
<languages />
{{Extension
|status = stable
|image = Screenshot of TemplateData extension.png
|type1 = tag
|type2 = api
|author = [[User:Krinkle|Timo Tijhof]], [[User:Mooeypoo|Moriel Schottlender]], [[User:Jdforrester (WMF)|James Forrester]], [[User:Trevor Parscal|Trevor Pascal]], [[User:Matma Rex|Bartosz Dziewoński]], Marielle Volz, ...
|description = <translate><!--T:1--> Allows to store, retrieve and visualise information about templates</translate>
|license = GPL-2.0
|update = <translate><!--T:2--> Continuous updates</translate>
|mediawiki = 1.25+. <translate><!--T:3--> TemplateData master is only supported with core's master; otherwise, use matching branches (e.g. TemplateData REL1_26 with core REL1_26, or matching WMF release branches).</translate>
|php = 5.4+
|hook1 = ParserFirstCallInit
|hook2 = PageContentSave
|hook3 = ResourceLoaderTestModules 
|hook4 = ResourceLoaderRegisterModules
|hook5 = EditPage::showEditForm:initial
|download = {{WikimediaDownload|TemplateData}}
|needs-updatephp = No
|readme =
|parameters = $wgTemplateDataUseGUI
|phabricator = TemplateData
|tags = {{tag|templatedata|open}}
}}
<translate>
<!--T:4-->
The '''TemplateData''' extension introduces a <tvar|1>{{tag|templatedata|open}}</> tag and an API which together allow editors to specify how templates should be invoked.</translate>
<translate>
<!--T:5-->
This information is available as a nicely-formatted table for end-users, and as a JSON API, which enables other systems (e.g. [[VisualEditor]]) to build interfaces for working with templates and their parameters.</translate>
<translate>
<!--T:6-->
See {{<tvar|1>ll|Help:TemplateData</>|Help:TemplateData}} for in-depth help.

== Installation == <!--T:7-->
</translate>
{{ExtensionInstall
|registration=yes
}}

<translate>
== Editing data == <!--T:8-->

<!--T:9-->
The TemplateData extension works through having a <tvar|1>{{tag|templatedata|open}}</> tag defined in the wikitext of a template page (optionally it can be transcluded from a different page as well).</translate>
<translate>
<!--T:10-->
This is designed to be compatible with the common layout many wikis have of transcluding template documentation from a separate page (but is not required).</translate>
<translate>
<!--T:11-->
This content of the <tvar|1>{{tag|templatedata|open}}</> tag must be valid JSON using the format described below; note that '''all descriptions must be in plain text''' (no wikitext is accepted inside the template data).

<!--T:12-->
When a <tvar|1>{{tag|templatedata|open}}</> block is included on a page, the TemplateData extension performs the following checks when the page is being saved:

<!--T:13-->
# The contents must be valid JSON;</translate>
<translate>
<!--T:14-->
# Each item within the JSON structure must be of the expected type as specified below (e.g. object, array, or a primitive); and</translate>
<translate>
<!--T:15-->
# For those items which have a specified list of possible values (e.g. <tvar|1><code>params.yourParameterName.type</code></>), the value in the JSON object must match one of those values.

<!--T:16-->
If any of these checks fails, the server will not be permitted saving and an error message will be displayed above the edit page.

<!--T:17-->
For autovalue items, [[<tvar|1>bugzilla:2700</>|bug 2700]] prevents <tvar|2><code>subst:</code></> from working in any template that is added inside a <tvar|3>{{tag|tag|open}}</>, including <tvar|4>{{tag|ref|open}}</> and <tvar|5>{{tag|gallery|open}}</> tags.</translate>
<translate>
<!--T:18-->
The TemplateData block will save correctly, but the resulting wikitext will not be parsed correctly when the template is used.

<!--T:19-->
Note that  you cannot use <tvar|1><code><nowiki>{{#tag:templatedata}}</nowiki></code></> in lieu of <tvar|2>{{tag|templatedata|open}}</>.
</translate>

===Format===

The below is a visualised version of the JSON data as defined on the template page enclosed by <code><nowiki><templatedata></nowiki></code><code><nowiki></templatedata></nowiki></code> tags. The formal specification is available in the TemplateData repository. Refer to [https://github.com/wikimedia/mediawiki-extensions-TemplateData/blob/master/Specification.md Specification.md] for the latest version.

{{anchor|TemplateData object|TemplateData Object}}
<translate>
====TemplateData object==== <!--T:26-->
</translate>
The TemplateData object is a ''JSON root element'' enclosed in a <code><nowiki><templatedata></nowiki></code> element on the template page.

{| class="wikitable"
|-
! <translate><!--T:27--> Key</translate>
! <translate><!--T:28--> Type</translate>
! <translate><!--T:29--> Description</translate>
|-
| <code>description</code>
| [[#InterfaceText (string or object)|InterfaceText]] or <code>null</code>
| A brief description of the template. '''It must be in plain text'''. Once filled, it can be displayed as caption when editing a single template and perhaps in search results when users pick one of many. The default is <code>null</code>.
|-
| <code>params</code>
| Object containing [[#Param object|Param objects]]
| An object that maps each parameter name of the template to a corresponding [[#Param object|Param object]] describing the properties of that parameter.
|-
| <code>paramOrder</code>
| Array containing parameter name strings
| The logical order in which parameters should be displayed. The array contains each parameter key exactly once. Each string must be a valid key in the <code>params</code> object. ''If this key does not exist in the <code><nowiki><templatedata></templatedata></nowiki></code> structure on the template page, it is added to the structure provided by the API using the order in which the parameters occur within the TemplateData object.''
|-
| <code>sets</code>
| Array containing <br/>[[#Set object|Set objects]]
| An array containing set specifications. A set is a group of parameters that should be used together. The default is []. Note that the <code>sets</code> functionality is still in development.
|-
| <code>format</code>
| string, either <code>inline</code> or <code>block</code>
| How the template's wikitext representation SHOULD be laid out. The default is <code>inline</code>. See [[Help:TemplateData#Custom_formats]] for other custom formats.
|-
| <code>maps</code>
| A [[#Maps object|Maps object]]
| An object that maps a simplified name of a third party consumer of the template data (i.e. [[Citoid]], [[Wikidata]], etc.) to an object that in turn maps a name of a consumer parameter to one or more corresponding names of template parameters.
|}

{{anchor|Param object|Parameter Object}}
<translate>
==== Param object ==== <!--T:30-->
</translate>
{| class="wikitable"
|-
! <translate><!--T:31--> Key</translate>
! <translate><!--T:32--> Type</translate>
! <translate><!--T:33--> Default</translate>
! <translate><!--T:34--> Description</translate>
|-
| <code>label</code> || [[#InterfaceText (string or object)|InterfaceText]]
| style="text-align: center;" | <code>null</code> || A (very) brief name for the parameter. Try to keep under 20-ish characters.
|-
| <code>description</code>
| [[#InterfaceText (string or object)|InterfaceText]]
| style="text-align: center;" | <code>null</code>
| A brief description of the parameter, for users to know which to pick from an option list.
|-
| <code>required</code>
| boolean
| style="text-align: center;" | <code>false</code>
| Whether the parameter is required for the template to work (true if this parameter '''must''' be specified).
|-
| <code>suggested</code>
| boolean
| style="text-align: center;" | <code>false</code>
| Whether the parameter is suggested for the template to be useful (true if this parameter '''should''' be specified).
|-
| <code>deprecated</code> || boolean or string
| style="text-align: center;" | <code>false</code> || Whether the parameter is deprecated. The value can be a string of instructions giving the user guidance what instead can be done, or be simply <code>true</code>.
|-
| <code>aliases</code> || Array containing strings
| style="text-align: center;" | <code>[]</code> || List of aliases. An alias is an alternative name for the parameter that may be used instead of (not in addition to) the primary name. Aliases are not documented in a separate Parameter object. If they need more information, they should be in their own property marked "deprecated".
|-
| <code>default</code> || [[#InterfaceText (string or object)|InterfaceText]]
| style="text-align: center;" | <code>null</code> || The default value used by the template if no value is assigned to the parameter, or a description thereof.
|-
| <code>autovalue</code> || string
| style="text-align: center;" | <code>null</code> || A dynamically-generated default value in wikitext, such as today's date or the editing user's name; this will often involve wikitext substitution, such as <code><nowiki>{{subst:CURRENTYEAR}}</nowiki></code>.
|-
|<code>example</code>
|[[#InterfaceText (string or object)|InterfaceText]]
| style="text-align: center;" | <code>null</code>
|An example text for the parameter, to help users fill in the proper value.
|-
| <code>type</code> || string
| style="text-align: center;" | <code>"unknown"</code> || The type of the parameter, for (soft) type hinting. One of:
{| class="wikitable" id="parameter types"
|-
! 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.
|-
| "boolean" || A boolean value ('1' for true, '0' for false, '<nowiki/>' for unknown), see [[wikipedia:Three-valued logic|three-valued logic]].
|-
| "date" || A date in ISO 8601 format, e.g. "2014-05-09" or "2014-05-09T16:01:12Z"
|-
| "url" || A URL, including protocol, e.g. <nowiki>"http://www.example.org", "https://example.org", or "//example.org"</nowiki>.
|-
| "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-template-name"
| A valid MediaWiki Template name for the current wiki.
|-
| "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.''
|-
| {{nowrap|"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 <code><nowiki>{{echo|before=<u>|after=</u>}}</nowiki></code>
|}
|-
| <code>inherits</code> || string
| style="text-align: center;" | ''none'' <br /> substituted || The name key of another parameter (must be a valid key in the <code>params</code> object). The current [[#Param object|Parameter Object]] will inherit properties from the specified [[#Param object|Parameter Object]], with local properties overriding the inherited ones.
|}

{{anchor|Set object|Set Object}}
<translate>
==== Set object ==== <!--T:35-->
</translate>
{| class="wikitable"
! <translate><!--T:36--> Key</translate>
! <translate><!--T:37--> Type</translate>
! <translate><!--T:38--> Default</translate>
! <translate><!--T:39--> Description</translate>
|-
| — 
| Array of Arrays
| style="text-align: center;" | <code>[]</code>  
| The type of the parameter, for (soft) type hinting. One of:
{| class="wikitable" id="Set"
|+
Set Object

!
Key 
!
Object or
primitive type 
!
Description
|-
| <code>label</code> 
| [[#InterfaceText (string or object)|InterfaceText]] 
| A (very) brief name for the parameter set. Try to keep under 20-ish characters.
|-
| <code>params</code> 
| Array of strings 
| One or more names of parameters to include in the set (each must be a valid key in the <code>params</code> object). A parameter may be in multiple sets. Not every parameter must be in a set.
|}
|}

{{anchor|Maps object|Maps Object}}
<translate>
==== Maps object ==== <!--T:40-->
</translate>
{| class="wikitable"
! <translate><!--T:41--> Key</translate>
! <translate><!--T:42--> Type</translate>
! <translate><!--T:43--> Default</translate>
! <translate><!--T:44--> Description</translate>
|-
| ''name of consumer''
| object
| style="text-align: center;" | {}  
| An object that maps a ''name of a consumer'' to an object that in turn maps a ''name of a consumer parameter'' to one or more corresponding ''names of template parameters''.

The ''names of the template parameters'' can be specified either as a string (one name), an array of strings (several names), or an array of arrays of strings (several sets of names); each of these strings must be a valid key in the <code>params</code> object elsewhere in the same template's TemplateData. 

A specific template parameter may be in multiple maps, and it may be used in the values of multiple keys in a given map, but not every template parameter ''must'' be in a map.

A shortened example from English Wikipedia's [[w:Template:Cite_news#TemplateData|Template:Cite_news#TemplateData]] illustrates the structure of a maps object.
<pre>
{
	"proveit": {
		"main": "title",
		"textarea": [
			"quote"
		]
	},
	"citoid": {
		"title": "title",
		"url": "url",
		"publisher": "publisher",
		"publicationTitle": "work",
		"date": "date",
		…
		"ISSN": [
			"issn"
		],
		"ISBN": [
			"isbn"
		],
		…
		"contributor": "others",
		"author": [
			[
				"first",
				"last"
			],
			[
				"first2",
				"last2"
			],
			…
			[
				"first9",
				"last9"
			]
		],
		"editor": [
			[
				"editor-first",
				"editor-last"
			]
		]
	}
}
</pre>
|}

{{anchor|InterfaceText (string or object)}}
<translate>
==== InterfaceText (string or object) ==== <!--T:45-->
</translate>
A free-form plain-text string (i.e. no wikitext or HTML) in the content-language of the wiki, or an object containing those strings keyed by language code.

The default value for all InterfaceText fields is <code>null</code>.

===== String type =====
If it is a string, it must contain a non-localized string in the content language of the local wiki.

===== Object type =====
If it is an object, the object must have this mapping:

{| class="wikitable" id="InterfaceText" style="width: 100%;"
|-
! Key !! Type !! Description
|-
| style="text-align: center;" |  ''[[:en:List of Wikipedias|Wikipedia language code]]'' || string || Localized string for use on the Wikipedia corresponding to the given language code.
|}Example of object mapping:

{| class="wikitable" id="InterfaceText" style="width: 100%;"
|-
! Key !! Value
|-
| style="text-align: center;" | "en" || "Welcome to Wikipedia"
|-
| style="text-align: center;" | "de" || "Willkommen bei Wikipedia"
|-
| style="text-align: center;" | "fe" || "Bienvenue sur Wikipédia"
|-
| style="text-align: center;" | "nl" || "Welkom op Wikipedia"
|-
| style="text-align: center;" | "it" || "Benvenuti su Wikipedia"
|-
| style="text-align: center;" | "es" || "Bienvenidos a Wikipedia"
|-
| style="text-align: center;" | "ru" || "Добро пожаловать в Википедию"
|}

=== Example ===
An example TemplateData structure as specified within wikitext on a template page.
<syntaxhighlight lang="javascript"><templatedata>
{
    "description": "Label unsigned comments in a conversation.",
    "params": {
        "user": {
            "label": "User's name",
            "type": "wiki-user-name",
            "required": true,
            "description": "User name of person who forgot to sign their comment.",
            "aliases": ["1"]
        },
        "date": {
            "label": "Date",
            "suggested": true,
            "description": {
                "en": "Timestamp of when the comment was posted, in YYYY-MM-DD format."
            },
            "aliases": ["2"],
            "autovalue": "{{subst:#time:Y-m-d}}"
        },
        "year": {
            "label": "Year",
            "type": "number"
        },
        "month": {
            "label": "Month",
            "inherits": "year"
        },
        "day": {
            "label": "Day",
            "inherits": "year"
        },
        "comment": {
            "required": false
        }
    },
    "sets": [
        {
            "label": "Date",
            "params": ["year", "month", "day"]
        }
    ],
    "maps": {
        "ExampleConsumer": {
            "foo": "user",
            "bar": ["year", "month", "day"],
            "quux": [
                "date",
                ["day", "month"],
                ["month", "year"],
                "year"
            ]
        }
    }
}
</templatedata>

Below is how the above example would be displayed on the template page:

Label unsigned comments in a conversation.

模板参数[编辑模板数据]

参数描述类型状态
User's nameuser 1

User name of person who forgot to sign their comment.

用户必需
Datedate 2

Timestamp of when the comment was posted, in YYYY-MM-DD format.

自动值
{{subst:#time:Y-m-d}}
未知推荐
Yearyear

无描述

数字可选
Monthmonth

无描述

数字可选
Dayday

无描述

数字可选
commentcomment

无描述

未知可选

API

See the generated help at Special:ApiHelp/templatedata. A sample invocation (formatted for human readability) is: 模板:ApiEx This returns the template data for Template:Cite web. The <templatedata>...</templatedata> block for this template is on its transcluded template documentation page, en:Template:Cite web/doc.

Additions and changes to JSON as received from the API

The JSON structure provided in response to an API HTTP get request is significantly different than that which is defined in the <templatedata>...</templatedata> block. In response to the API request, extension TemplateData makes the following changes to the JSON object:

  1. An overall Pages Object containing one or more Page Objects
  2. An object with a numeric key: a Page Object
  1. Add the title key with the name of the page from which the data was requested (e.g. "Template:Cite web").
  2. Add the paramOrder key and array using the order in which the parameters occur in the params key within the TemplateData Object on the template page.
  3. Add the sets key
  4. Change all TemplateText occurrences that are just strings to objects with a single key for the current wiki's Wikipedia language code
  5. Remove all inherits keys.
  • Add all properties from parameter from which an inheritance is defined which are not superseded by explicitly defined keys in the inheritor's Parameter Object.
  1. Add default values for all keys in each Parameter Object which have not been explicitly defined or inherited.

Visualised differences in a TemplateData JSON object delivered by the API

Wrapper objects added to JSON delivered by API
These are not defined in the JSON object enclosed by the <templatedata> tags on the template page.
JSON Root
Key Type Description
pages Page Object The page object (contains one key which is the page number). If multiple pages were requested at one time there will be multiple Page Objects.

Page Object
Key Type Description
(page number) TemplateData Object The TemplateData Object containing the information payload. The key is a static page number for the template page from which the JSON data was requested.


TemplateData Object (added by API)
The following key is added to the root of the JSON object which is enclosed in <templatedata> tags on the template page.
Key Type Default Description
title string The page name of the template (e.g. "Template:Cite web").
This key is not contained in the JSON structure on the template page. It is added to the structure by the MediaWiki software in route to delivery via the API.
paramOrder Array containing parameter name strings The logical order in which parameters should be displayed. The array contains each parameter key exactly once. Each string must be a valid key in the params object.
If this does not exist in the <templatedata></templatedata> structure on the template page, it is added to the structure as provided by the API using the order in which the parameters occur within the TemplateData object.
sets Array containing Set Objects An array containing set specifications. A set is a group of parameters that should be used together.
If this does not exist on the template page it is added as an empty array to the structure provided by the API.


Parameter Objects from API
Key Type Description
label InterfaceText translated to InterfaceText object, if not already in that format.
required boolean If not defined, default value of false added.
description InterfaceText or null If defined as a string, converted to a InterfaceText object. If not defined, key is added with a null value.
deprecated boolean or string If not defined, default value of false added.
aliases Array of strings If not defined, a default empty array is assigned (i.e. [] ).
default string If not defined, default of "" is assigned.
type string If not defined, default of "unknown" is assigned.
inherits removed This key is removed and all inherited keys are added. Keys defined for the current parameter take precedence and any keys not defined on either the current param, or the one from which it inherits are given the default value.


InterfaceText (Object or null):
An object containing strings keyed by language code.
Key Object or
primitive type
Description
Object
(containing localized strings by Wikipedia language code)
If a TemplateData field on the template page contains a string, not an object with localized strings, MediaWiki translates it into an InterfaceText Object with a string assigned to the key name of the source Wikipedia Wikipedia language code. The default for all InterfaceText fields is null.
(Wiki language code) string Localized string for use on the Wikipedia corresponding to the Wikipedia language code.


Example of JSON object provided by API

The response to an API request for the TemplateData structure in the Example of TemplateData structure WikiText on template page section (above) can be seen:

<translate>

Configuration

</translate>

<translate> Variable</translate> <translate> Default</translate> <translate> Description</translate>
$wgTemplateDataUseGUI true <translate> Experimental dialog interface to edit templatedata JSON</translate>

<translate>

See also

</translate>

  • 模板:Ll – user interface for selecting and inserting templates' wikitext, based on their TemplateData.
  • GitHub: jeblad/TemplateData – alternate version with some Lua functionality.

模板:OnWikimedia

[[Category:Metadata{{#translation:}}]] </syntaxhighlight>