Расширение:Variables
![]() Статус релиза: стабильно |
|
---|---|
Реализация | Функция парсера |
Описание | Introduces parser functions for dealing with page-scoped variables. |
Автор(ы) |
|
Поддерживающий(ие) | MGChecker |
Последняя версия | 2.5.1 (2019-07-11) |
MediaWiki | 1.29+ |
PHP | 5.5+ |
Изменения в БД | Нет |
Composer | mediawiki/variables |
Лицензия | ISC License |
Скачать | README RELEASE-NOTES |
|
|
Ежеквартальные загрузки | 203 (Ranked 42nd) |
Использование общедоступными вики | 1,808 (Ranked 201st) |
Переведите расширение Variables, если оно доступно на translatewiki.net | |
Роль Vagrant | variables |
Проблемы | Открытые задачи · Сообщить об ошибке |
Расширение Variables позволяет вам определить переменную на странице, использовать ее позже на той же странице или включить шаблоны, изменить ее значение, возможно, на значение, заданное выражением в терминах старого значения и т. д.
Это похоже на шаблоны, только более лёгкое и ограничено только одной страницей, поэтому вы можете использовать множество переменных на странице, не замедляя вики с огромным количеством шаблонов. Объедините это расширение с расширением Расширение:ParserFunctions для достижения наилучших результатов.
#var_final
parser function is shown as deprecated in MediaWiki 1.35 or above, due to changes in the parser. However, it will continue to work in this versions. See задача T276627 and задача T236809 for further information.
Присвоение значения переменной
#vardefine
{{#vardefine:variablename|specifiedvalue}}
Присваивает значение specifiedvalue (уже существующей или введенной) переменной variablename.
- Пример:
{{#vardefine:iconwidth|25}}
присваиваетiconwidth = 25
#vardefineecho
{{#vardefineecho:variablename|specifiedvalue}}
Работает так же, как #vardefine
но выводит затронутые значения.
- Пример: making
iconwidth = {{#vardefineecho:iconwidth|25}}
Получение значения переменной
#var
The value of the variable variablename is produced by
{{#var:variablename}}
If undefined, this produces an empty string; it does not give an error message.
Можно определить значение для случая, когда переменная не определена или void:
{{#var:variablename | defaultvalue }}
This is equivalent to:
{{#if: {{#var:variablename}} | {{#var:variablename }} | defaultvalue }}
but it is much shorter and better arranged. Before version 2.0 though, the default value always was expanded. From version 2.0 on the default only gets expanded in case it is actually used.
The value can be used in parser functions, etc.
#varexists
{{#varexists:variablename }}
returns 1 if the variable is already defined. If the variable is not defined the return value is void.
It supports a second and a third parameter to replace these values.
{{#varexists:variablename | if-value | else-value }}
This is equivalent to:
{{#if: {{#varexists: variablename }} | if-value | else-value }}
but it is much shorter and better arranged. Before version 2.5 though, both were always expanded. From version 2.5 on the if and else values only get expanded when their cases are actually entered.
#var_final
Experimental function introduced in Variables 2.0. This function will output the final, last value a variable has at the end of the page rendering. Naturally, the value will be inserted after the parser went over the entire wiki markup, so this function can't be used in other functions, expecting the right value is being used. Example:
{{#var_final:variablename | defaultvalue}}
Значение default будет использоваться, если переменная не существует на этапе рендеринга последней страницы или если ее значение является пустой строкой. Значение по умолчанию будет расширяться прямо там, где используется функция, поэтому параметр будет расширен, даже если он не понадобится.
Примеры
The Расширение:ParserFunctions extension must also be installed to use #expr
.
Compute x = 2*a + b
:
{{#vardefine:x|{{#expr:2*{{#var:a}}+{{#var:b}}}}}}
Add one to n:
{{#vardefine:n|{{#expr:{{#var:n}}+1}}}}
Установка
- Скачайте и распакуйте файл(ы) в папку с названием
Variables
в вашей папкеextensions/
. - Добавьте следующий код в конце вашего файла LocalSettings.php :
wfLoadExtension( 'Variables' );
- Configure as required
Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.
Для использующих MediaWiki 1.30 или более ранние версии:
В приведенных выше инструкциях описывается новый способ установки этого расширения с использованием wfLoadExtension()
.
Если вам нужно установить это расширение на более ранние версии (MediaWiki 1.30 и более ранние), вместо wfLoadExtension( 'Variables' );
, вам необходимо использовать:
require_once "$IP/extensions/Variables/Variables.php";
Конфигурация
This extension provides two configuration parameters:
$egVariablesAreVolatile
- Allows to disable the parser frame being marked as volatile by the extension, i.e. disable template caching.
- По умолчанию:
true;
$egVariablesDisabledFunctions
- Allows to disable specified parser functions provided by this extension.
- Default:
[];
- Пример:
[ 'var_final', 'vardefineecho' ];
Совместимость
The recommended version of the Variables extension for recent MediaWiki releases is listed below. Older versions of the extensions might work as well, but aren't tested for new MediaWiki releases.
1.19 | 1.20 | 1.21 | 1.22 | 1.23 | 1.24 | 1.25 | 1.26 | 1.27 | 1.28 | 1.29 | 1.30 | 1.31 | 1.32 | 1.33 | 1.34 | master | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2.x | 2.1.x | 2.2.x | 2.5.x, master |
Alternatives
As this extension will not be enabled for wikis run by the Wikimedia Foundation (WMF), here are some alternatives:[1][2][3][4]
- If you use Variables as cache for expensive operations, you can transform the section where you need them into a template and pass the required information as template parameters instead. This will work until you reach the expansion depth limit, which can be increased if necessary.
- If you use Variables to do more complex template operations than possible with simple Расширение:ParserFunctions , and if you have sufficient permissions on the server, you can use Scribunto's Lua functionality instead. You may not be able to install Scribunto on shared hosting. Note that this does not add support for global Variables. However, Extension:VariablesLua adds a Scribunto interface for the Variables store.
- Don't use variables, instead duplicate the information you need as a variable. If that information is acquired by an expensive template call, performance may suffer. This will work until you reach the node count limit.
- If you require variables just for autonumbering, you could look into Extension:NumerAlpha .
Смотрите также
- Расширение:PhpTags
- Расширение:MyVariables - Creates new variables in the MediaWiki sense
- Расширение:Циклы — Provides parser functions for performing loops
- Расширение:Arrays — Create an array and provide array functions (such as search, split, and sort) and set operations (such as intersect, union and diff)
- Extension:HashTables — New parser functions for handling hash tables in MediaWiki
References
- ↑ 1.0 1.1 phab:T9865
- ↑ 2.0 2.1 phab:T65324
- ↑ 3.0 3.1 phab:T113859
- ↑ 4.0 4.1 phab:T151192
![]() | Это расширение включено в следующие вики-фермы/хостинги и/или пакеты: Это не исчерпывающий список. Некоторые вики-фермы/хостинги и/или пакеты могут содержать это расширение, даже если они не перечислены здесь. Всегда сверяйтесь со своими вики-фермами/хостингами или комплектами/бандлами для подтверждения. |
- Stable extensions/ru
- Parser function extensions/ru
- Extensions supporting Composer/ru
- ISC licensed extensions/ru
- Extensions in Wikimedia version control/ru
- InternalParseBeforeSanitize extensions/ru
- ParserClearState extensions/ru
- ParserFirstCallInit extensions/ru
- All extensions/ru
- Extensions included in BlueSpice/ru
- Extensions included in Canasta/ru
- Extensions included in Fandom/ru
- Extensions included in Miraheze/ru
- Extensions included in Open CSP/ru
- Extensions included in ProWiki/ru
- Extensions included in semantic::core/ru
- Extensions included in wiki.gg/ru
- Extensions included in WikiForge/ru
- Extensions included in WikiTide/ru
- Modifiable variables extensions/ru