Расширение:TemplateData

From mediawiki.org
This page is a translated version of the page Extension:TemplateData and the translation is 24% complete.
Это расширение поставляется с MediaWiki 1.35 и выше. Таким образом, вам не нужно загружать его снова. Тем не менее, вы всё равно должны следовать другим инструкциям.
Справка по расширениям MediaWiki
TemplateData
Статус релиза: стабильно
Реализация Тег , API
Описание Позволяет хранить, получать и визуализировать информацию о шаблонах
Автор(ы) Timo Tijhof, Moriel Schottlender, James Forrester, Trevor Parscal, Bartosz Dziewoński, Marielle Volz, ...
Последняя версия 0.1.2 (Постоянные обновления)
Политика совместимости Snapshots releases along with MediaWiki. Master is not backward compatible.
MediaWiki 1.25+
PHP 5.4+
Изменения в БД Нет
Лицензия GNU General Public License 2.0 или позднее
Скачать
  • $wgTemplateDataUseGUI
‎<templatedata>
Ежеквартальные загрузки 358 (Ranked 23rd)
Использование общедоступными вики 6,971 (Ranked 24th)
Переведите расширение TemplateData, если оно доступно на translatewiki.net
Проблемы Открытые задачи · Сообщить об ошибке

Расширение TemplateData вводит тег ‎<templatedata> и API, которые вместе позволяют редакторам указывать, как следует использовать шаблоны и их параметры. Эта информация доступна в виде красиво отформатированной таблицы для конечных пользователей и в виде API в формате JSON, который позволяет другим системам (например, VisualEditor) создавать интерфейсы для работы с шаблонами. Смотрите Help:TemplateData для детальной информации.

Установка

  • Скачайте и распакуйте файл(ы) в папку с названием TemplateData в вашей папке extensions/.
  • Добавьте следующий код в конце вашего файла LocalSettings.php :
    wfLoadExtension( 'TemplateData' );
    
  • Yes Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.

Редактирование данных

Расширение TemplateData работает при помощи тэга ‎<templatedata>, определенного в вики-разметке на странице шаблона (по желанию он также может быть включен из другой страницы). Оно было разработано, чтобы быть совместимым с общим макетом, который есть во многих вики, включая документацию шаблона с отдельной страницы (но не обязательно). Содержимое тега ‎<templatedata> должно быть валидным JSON, использующим описанный ниже формат; обратите внимание, что все описания должны быть простым текстом (в данных шаблонах не должно присутствовать вики-разметки).

Когда ‎<templatedata> помещён на страницу, расширение TemplateData выполняет следующие проверки при сохранении:

  1. Содержание должно быть валидным JSON;
  2. Каждый элемент JSON должен соответствовать указанному ниже типу (т. е. объект, массив или примитивный тип); и
  3. Для элементов, имеющих список возможных значений (например, параметра type), значение в объекте JSON должно соответствовать одному из этих значений.

В случае нарушения этих условий сервер не позволит сохранить изменения, и над страницей редактирования появится сообщение об ошибке.

Для элементов с автоматическим значением T4700 предотвращает работу subst: в любом шаблоне, добавленном внутри тега, включая теги ‎<ref> и ‎<gallery>. Блок TemplateData будет сохранен правильно, но полученная вики-разметка не будет правильно проанализирована при использовании шаблона.

Пожалуйста, избегайте использования {{#tag:templatedata}}, поскольку это делает невозможным использование редактора данных шаблона.

Формат

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

The TemplateData object is a JSON root element enclosed in a ‎<templatedata> element on the template page.

Ключ Тип Описание
description InterfaceText или 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. Значение по умолчанию: 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.
sets Array containing
Set objects
An array containing set specifications. A set is a group of parameters that should be used together. Значение по умолчанию: []. Заметьте, что функциональность sets всё ещё в разработке.
format строка, inline либо block How the template's wikitext representation SHOULD be laid out. Значение по умолчанию: 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.

Объект параметра

Ключ Тип По умолчанию Описание
label InterfaceText null (Очень) короткое имя параметра. Старайтесь не превышать длину в более чем 20 символов.
description InterfaceText null Короткое описание параметра, чтобы пользователи знали, что выбирать из списка.
required булево значение false Обозначает, необходим ли параметр для работы шаблона (true, если параметр должен быть указан).
suggested булево значение false Whether the parameter is suggested for the template to be useful (true if this parameter should be specified).
deprecated булево значение либо строка 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 Массив из строк [] Список псевдонимов. Псевдоним — это альтернативное имя для параметра, которое может быть использовано вместо (не в дополнение) основного. 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 строка 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 строка "unknown" The type of the parameter, for (soft) type hinting. One of:
Значение строки Тип параметра
"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, '' for unknown), see 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. "http://www.example.org", "https://example.org", or "//example.org".
"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.
"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>}}
inherits строка нет
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.
suggestedvalues Array containing strings [] An optional parameter property. Creates a list of parameter values to help users select the desired value. For the suggested values to be displayed as a combo box in VisualEditor, the parameter’s type must be set to one of the following: content, line, string, number, unknown or unbalanced wikitext.

Set object

Key

Object or primitive type

Description

label InterfaceText A (very) brief name for the parameter set. Try to keep under 20-ish characters.
params Array of strings One or more names of parameters to include in the set (each must be a valid key in the params object). A parameter may be in multiple sets. Not every parameter must be in a set.

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 params 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 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 users of that interface language.

Example of object mapping:

Key Value
"en" "Welcome to Wikipedia"
"de" "Willkommen bei Wikipedia"
"fr" "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.

Template parameters

ParameterDescriptionTypeStatus
User's nameuser 1

User name of person who forgot to sign their comment.

Userrequired
Datedate 2

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

Auto value
{{subst:#time:Y-m-d}}
Unknownsuggested
Yearyear

no description

Numberoptional
Monthmonth

no description

Numberoptional
Dayday

no description

Numberoptional
commentcomment

no description

Unknownoptional

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:

    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 sets key
    3. Change all TemplateText occurrences that are just strings to objects with a single key for the current wiki's Wikipedia language code
    4. 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.
    5. 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
{{{1}}} 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 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.
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 (удалено) 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 users of that interface language.

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:

Настройка

Переменная По умолчанию Описание
$wgTemplateDataUseGUI true Экспериментальный диалоговый интерфейс для TemplateData JSON

См. также