Розширення:дані шаблону
TemplateData Статус релізу: стабільний |
|
---|---|
![]() |
|
Реалізація | Tag , API |
Опис | Дозволяє зберігати, отримувати та візуалізувати інформацію про шаблони |
Автор(и) | Timo Tijhof, Moriel Schottlender, James Forrester, Trevor Pascal, Bartosz Dziewoński, Marielle Volz, ... |
Найновіша версія | 0.1.2 (Постійні оновлення) |
Compatibility policy | Snapshots releases along with MediaWiki. Master is not backwards compatible. |
MediaWiki | 1.25+ |
PHP | 5.4+ |
Зміни в БД | No |
Ліцензія | GNU General Public License 2.0 or later |
Завантажити | |
|
|
<templatedata> |
|
Translate the TemplateData extension if it is available at translatewiki.net | |
Issues | Open tasks · Report a bug |
Розширення TemplateData виводить тег <templatedata>
та API, які разом дозволяють редакторам вказувати, як слід викликати шаблони.
Ця інформація доступна як гарно відформатована таблиця для кінцевих користувачів, і як JSON API, який дозволяє іншим системам (наприклад, VisualEditor) будувати інтерфейси для роботи зі шаблонами та їхніми параметрами.
Поглиблену довідку див. на Help:TemplateData#Custom formats .
Встановлення
- Завантажте і розмістіть файли в каталозі з назвою
TemplateData
у вашійextensions/
папці. - Додайте такий код унизу вашого LocalSettings.php:
wfLoadExtension( 'TemplateData' );
- Готово – Перейдіть до Special:Version вашої вікі, щоб переконатися, що розширення встановлено успішно.
Редагування даних
Розширення TemplateData працює через визначення тегу <templatedata>
у вікі-тексті сторінки шаблону (необов'язково його можна включити і з іншої сторінки).
Його розроблено для сумісності зі спільним компонуванням багатьох вікіпедій включення документації шаблонів з окремих сторінок (але не вимагається).
Цей вміст тегу <templatedata>
повинен бути дійсним JSON, використовуючи нижчеописаний формат; зауважте, що всі описи повинні бути у простому тексті (вікі-текст неприйнятний усередині даних шаблонів).
При включенні блоку <templatedata>
на сторінку розширення TemplateData виконує наступні перевірки при збереженні сторінки.
- Вміст повинен бути дійсним JSON;
- Кожен елемент структури JSON повинен бути очікуваного типу, як зазначено нижче (наприклад, об'єкт, масив або примітив); і
- Для елементів із визначеним списком можливих значень (наприклад,
params.yourParameterName.type
) значення в об'єкті JSON повинно відповідати одному з тих значень.
Якщо будь-яка з перевірок не вдається, серверу не дозволяється збереження, а над сторінкою редагування показується повідомлення про помилку.
Для елементів із автоматичним значенням помилка 2700 запобігає спрацюванню subst:
у будь-якому шаблоні, доданому всередині <tag>
, включаючи теги <ref>
і <gallery>
.
Блок TemplateData коректно зберігатиметься, але результатний вікі-текст не аналізуватиметься коректно при використанні шаблону.
Зауважте, що не можна використовувати {{#tag:templatedata}}
замість <templatedata>
.
Format
The below is a visualised version of the JSON data as defined on the template page enclosed by <templatedata>
</templatedata>
tags.
The formal specification is available in the TemplateData repository. Refer to Specification.md for the latest version.
TemplateData object
The TemplateData object is a JSON root element enclosed in a <templatedata>
element on the template page.
Key | Type | Description |
---|---|---|
description
|
InterfaceText or null
|
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 null .
|
params
|
Object containing Param objects | An object that maps each parameter name of the template to a corresponding Param object describing the properties of that parameter. |
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 key does not exist in the <templatedata></templatedata> 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.
|
sets
|
Array containing 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 sets functionality is still in development.
|
format
|
string, either inline or block
|
How the template's wikitext representation SHOULD be laid out. The default is inline . See #Custom_formats for other custom formats.
|
maps
|
A Maps object | An object that maps a simplified name of a third party consumer of the template data (i.e. Citoid, Special:MyLanguage/Wikidata, etc.) to an object that in turn maps a name of a consumer parameter to one or more corresponding names of template parameters. |
Param object
Key | Type | Default | Description | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
label |
InterfaceText | null |
A (very) brief name for the parameter. Try to keep under 20-ish characters. | ||||||||||||||||||||||||||||
description
|
InterfaceText | null
|
A brief description of the parameter, for users to know which to pick from an option list. | ||||||||||||||||||||||||||||
required
|
boolean | false
|
Whether the parameter is required for the template to work (true if this parameter must be specified). | ||||||||||||||||||||||||||||
suggested
|
boolean | false
|
Whether the parameter is suggested for the template to be useful (true if this parameter should be specified). | ||||||||||||||||||||||||||||
deprecated |
boolean or string | false |
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 true .
| ||||||||||||||||||||||||||||
aliases |
Array containing strings | [] |
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". | ||||||||||||||||||||||||||||
default |
InterfaceText | null |
The default value used by the template if no value is assigned to the parameter, or a description thereof. | ||||||||||||||||||||||||||||
autovalue |
string | null |
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 {{subst:CURRENTYEAR}} .
| ||||||||||||||||||||||||||||
example
|
InterfaceText | null
|
An example text for the parameter, to help users fill in the proper value. | ||||||||||||||||||||||||||||
type |
string | "unknown" |
The type of the parameter, for (soft) type hinting. One of:
| ||||||||||||||||||||||||||||
inherits |
string | none substituted |
The name key of another parameter (must be a valid key in the params object). The current Parameter Object will inherit properties from the specified Parameter Object, with local properties overriding the inherited ones.
|
Set object
Key | Type | Default | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
— | Array of Arrays | []
|
The type of the parameter, for (soft) type hinting. One of:
|
Maps object
Key | Type | Default | Description |
---|---|---|---|
name of consumer | object | {} | 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 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 Template:Cite_news#TemplateData illustrates the structure of a maps object. { "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" ] ] } } |
InterfaceText (string or object)
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 null
.
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:
Key | Type | Description |
---|---|---|
Wikipedia language code | string | Localized string for use on the Wikipedia corresponding to the given language code. |
Example of object mapping:
Key | Value |
---|---|
"en" | "Welcome to Wikipedia" |
"de" | "Willkommen bei Wikipedia" |
"fe" | "Bienvenue sur Wikipédia" |
"nl" | "Welkom op Wikipedia" |
"it" | "Benvenuti su Wikipedia" |
"es" | "Bienvenidos a Wikipedia" |
"ru" | "Добро пожаловать в Википедию" |
Example
An example TemplateData structure as specified within wikitext on a template page.
<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.
Parameter | Description | Type | Status | |
---|---|---|---|---|
User's name | user 1 | User name of person who forgot to sign their comment. | User | required |
Date | date 2 | Timestamp of when the comment was posted, in YYYY-MM-DD format.
| Unknown | suggested |
Year | year | no description | Number | optional |
Month | month | no description | Number | optional |
Day | day | no description | Number | optional |
comment | comment | no description | Unknown | optional |
API
See the generated help at Special:ApiHelp/templatedata.
A sample invocation (formatted for human readability) is:
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:
- Adds two wrapping objects:
- An overall Pages Object containing one or more Page Objects
- An object with a numeric key: a Page Object
- Additions/changes to the actual TemplateData Object
- Add the
title
key with the name of the page from which the data was requested (e.g. "Template:Cite web"). - Add the
paramOrder
key and array using the order in which the parameters occur in theparams
key within the TemplateData Object on the template page. - Add the
sets
key - Change all TemplateText occurrences that are just strings to objects with a single key for the current wiki's Wikipedia language code
- 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.
- Add default values for all keys in each Parameter Object which have not been explicitly defined or inherited.
- Add the
Visualised differences in a TemplateData JSON object delivered by the API
| ||||||
|
Key | Type | 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. |
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. |
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 section (above) can be seen:
- As delivered by the API: https://www.mediawiki.org/w/api.php?action=templatedata&titles=Extension:TemplateData
Конфігурація
Змінна | Замовчування | Опис |
---|---|---|
$wgTemplateDataUseGUI
|
true
|
Експериментальний діалоговий інтерфейс для редагування templatedata JSON |
Див. також
- Extension:TemplateWizard – user interface for selecting and inserting templates' wikitext, based on their TemplateData.
- GitHub: jeblad/TemplateData – alternate version with some Lua functionality.
Це розширення використовується в одному або декількох проектах Вікімедіа. Це, мабуть, означає, що розширення стабільне і працює досить добре, щоб його могли використовувати веб-сайти з великим трафіком. Шукайте назву цього розширення у файлах конфігурації Wikimedia CommonSettings.php та InitialiseSettings.php, щоб побачити, де це встановлене. Повний перелік розширень, встановлених на певній вікі, можна переглянути на сторінці Special:Version вікі. |