Справка:Расширение:Функции Парсера
Расширение Расширение:ParserFunctions предоставляет одиннадцать дополнительных функций парсера в дополнение к «волшебным словам », которые уже присутствуют в МедиаВики. (Может быть сконфигурировано для предоставления дополнительных функций синтаксического анализа при обработке строк; эти строковые функции задокументированы в другом месте .) Все функции парсера, предоставляемые этим расширением, имеют вид:
{{#имя_функции: аргумент 1 | аргумент 2 | аргумент 3 … }}
#expr
Тип | Операторы |
---|---|
Группировка (круглые скобки) | ( )
|
Числа | 1234.5 e (2.718) pi (3.142)
|
бинарный оператор e унарные + ,-
| |
Унарные | not ceil trunc floor abs exp ln sin cos tan acos asin atan
|
Бинарные | ^
|
* / div mod
| |
+ -
| |
Округление | round
|
Логические | = != <> > < >= <=
|
and
| |
or
|
Эта функция вычисляет математическое выражение и возвращает вычисленное значение.
Эта функция также доступна в Расширение:Scribunto через функцию mw.ext.ParserFunctions.expr
.
{{#expr: выражение }}
Доступные операторы перечислены справа в порядке очередности. Дополнительные сведения о функции каждого оператора см. в Справка:Вычисления. Точность и формат возвращаемого результата будут варьироваться в зависимости от операционной системы сервера, на котором выполняется вики, и числового формата языка сайта.
При вычислении с помощью булева алгебры ноль вычисляется как ложь
, а любое не нулевое значение, положительное или отрицательное, вычисляется как истина
:
{{#expr: 1 and -1 }}
→ 1{{#expr: 1 and 0 }}
→ 0{{#expr: 1 or -1 }}
→ 1{{#expr: -1 or 0 }}
→ 1{{#expr: 0 or 0 }}
→ 0
Пустое входное выражение возвращает пустую строку. Недопустимые выражения возвращают одно из нескольких сообщений об ошибке, которые могут быть перехвачены с помощью функции #iferror
:
{{#expr: }}
→{{#expr: 1+ }}
→ Expression error: Missing operand for +.{{#expr: 1 = }}
→ Expression error: Missing operand for =.{{#expr: 1 foo 2 }}
→ Expression error: Unrecognized word "foo".
Порядок сложения и вычитания операндов до или после числа имеет смысл и может рассматриваться как положительное или отрицательное значение, а не как операнд с ошибочным вводом:
{{#expr: +1 }}
→ 1{{#expr: -1 }}
→ -1{{#expr: + 1 }}
→ 1{{#expr: - 1 }}
→ -1
Обратите внимание, что при использовании вывода Волшебных слов, вы должны raw-форматировать их, чтобы удалить запятые и перевести цифры. Например, {{NUMBEROFUSERS}} результаты в 17 467 579, когда мы хотим 17467579, которые можно получить с помощью {{formatnum :{{NUMBEROFUSERS}}|R}}
. Это особенно важно в некоторых языках, где цифры переводятся. Например, в бенгальском языке {{NUMBEROFUSERS}} производит ৩০,০৬১.
{{#expr:{{NUMBEROFUSERS}}+100}}
→ Expression error: Unrecognized punctuation character " ".{{#expr:{{formatnum:{{NUMBEROFUSERS}}|R}}+100}}
→ 17467679
Округление
Округление число слева до кратного 1/10, возведенного в степень, с показателем степени, равным усеченному значению числа, заданного справа.
Для округления увеличением или уменьшением используйте унарные ceil
или floor
соответственно.
Тестовый пример | Результат | Метод округления |
---|---|---|
{{#expr: 1/3 round 5 }} |
0.33333 | Конечная цифра < 5, поэтому явного округления не происходит |
{{#expr: 1/6 round 5 }} |
0.16667 | Конечная цифра ≥ 5, поэтому она округляется |
{{#expr: 8.99999/9 round 5 }} |
1 | Опять же, результат округляется до последней цифры, что приводит к дополнительному округлению |
{{#expr: 1234.5678 round -2 }} |
1200 | Округляется до ближайшей 100, так как отрицательные значения округляются слева от десятичной запятой |
{{#expr: 1234.5678 round 2 }} |
1234.57 | Округляется до ближайшей 100-ой, потому что положительные значения округляются справа от десятичной запятой |
{{#expr: 1234.5678 round 2.3 }} |
1234.57 | Десятичные дроби в индексе округления не влияют на результат округления |
{{#expr: trunc 1234.5678 }} |
1234 | Десятичная часть отсечена (отброшена) |
Округление до ближайшего целого числа | ||
{{#expr: 1/3 round 0 }} |
0 | Уменьшение до "ближайшего" целого числа, которое равно нулю |
{{#expr: 1/2 round 0 }} |
1 | Увеличение до ближайшего целого числа, которое равно единице |
{{#expr: 3/4 round 0 }} |
1 | Увеличение до ближайшего целого числа, которое равно единице |
{{#expr: -1/3 round 0 }} |
-0 | Увеличение до ближайшего целого числа, которое равно нулю |
{{#expr: -1/2 round 0 }} |
-1 | Уменьшение до ближайшего целого числа, которое равно отрицательной единице |
{{#expr: -3/4 round 0 }} |
-1 | Уменьшение до ближайшего целого числа, которое равно отрицательной единице |
Округление увеличением или уменьшением с помощью "ceil" и "floor" | ||
{{#expr: ceil(1/3) }} |
1 | Увеличение до следующего "большего" целого числа, которое равно единице |
{{#expr: floor(1/3) }} |
0 | Уменьшение до следующего "меньшего" целого числа, которое равно нулю |
{{#expr: ceil(-1/3) }} |
-0 | Увеличение до следующего большего целого числа, которое равно нулю |
{{#expr: floor(-1/3) }} |
-1 | Уменьшение до следующего меньшего целого числа, которое является отрицательной единицей |
{{#expr: ceil 1/3 }} |
0.33333333333333 | Не округлялось, так как 1 уже является целым числом |
Строки
Выражения работают только с числовыми значениями, они не могут сравнивать строки или символы. Вместо этого можно использовать #ifeq.
{{#expr: "a" = "a" }}
→ Expression error: Unrecognized punctuation character """.{{#expr: a = a }}
→ Expression error: Unrecognized word "a".{{#ifeq: a | a | 1 | 0 }}
→ 1
#if
Функция определяет, является тестовая строка пустой или нет. Строка, содержащая только пробелы, считается пустой.
{{#if: тестовая строка | значение, если тестовая строка не пустая | значение, если тестовая строка пустая (или только пробелы) }}
{{#if: первый параметр | второй параметр | третий параметр }}
Эта функция сначала проверяет, не пуст ли первый параметр. Если первый параметр не пуст, то функция выводит второй аргумент. Если первый параметр пуст или содержит только пробельные символы (пробелы, новые строки и т. д.) он отображает третий аргумент.
{{#if: | yes | no}}
→ no{{#if: string | yes | no}}
→ yes{{#if: | yes | no}}
→ no{{#if:
→ no
| yes | no}}
Тестовая строка всегда интерпретируется как чистый текст, поэтому математические выражения не вычисляются:
{{#if: 1==2 | yes | no }}
→ yes{{#if: 0 | yes | no }}
→ yes
Последний параметр (ложь) может быть опущен:
{{#if: foo | yes }}
→ yes{{#if: | yes }}
→{{#if: foo | | no}}
→
Функция может быть вложенной. Для этого вложите внутреннюю функцию #if в ее полном виде вместо параметра заключающей функции #if. Возможно до семи уровней вложенности, хотя это может зависеть от Вики или ограничения памяти.
{{#if: тестовая строка | значение, если тестовая строка не пуста | {{#if: тестовая строка | значение, если тестовая строка не пуста | значение, если тестовая строка пуста (или только пробел) }} }}
Вы также можете использовать параметр в качестве тестовой строки в операторе #if. Вы должны убедиться, что вы добавляете |
(символ pipe) после имени переменной.
(Таким образом, если параметр не имеет значения, он вычисляется в пустую строку вместо строки "{{{1}}}
".)
{{#if:{{{1|}}}| Вы ввели текст в переменную 1|Нет текста в переменной 1 }}
Дополнительные примеры этой функции парсера см. в разделе Справка:Функции парсера в шаблонах .
#ifeq
Эта функция парсера сравнивает две входные строки, определяет, идентичны ли они, и возвращает одну из двух строк на основе результата.
Если требуется больше сравнений и выходных строк, рассмотрите возможность использования #switch
.
{{#ifeq: string 1 | string 2 | value if identical | value if different }}
Если обе строки являются допустимыми числовыми значениями, то строки сравниваются численно:
{{#ifeq: 01 | 1 | equal | not equal}}
→ equal{{#ifeq: 0 | -0 | equal | not equal}}
→ equal{{#ifeq: 1e3 | 1000 | equal | not equal}}
→ equal{{#ifeq: {{#expr:10^3}} | 1000 | equal | not equal}}
→ equal
В противном случае сравнение производится как текст; это сравнение чувствительно к регистру:
{{#ifeq: foo | bar | equal | not equal}}
→ not equal{{#ifeq: foo | Foo | equal | not equal}}
→ not equal{{#ifeq: "01" | "1" | equal | not equal}}
→ not equal (сравните с аналогичным примером выше, без кавычек){{#ifeq: 10^3 | 1000 | equal | not equal}}
→ not equal (сравните с аналогичным примером выше, с#expr
, возвращающим сначала допустимое число)
В качестве практического примера рассмотрим существующий шаблон Шаблон:Таймер
, использующий синтаксический анализатор для выбора между двумя стандартными временами, коротким и длинным.
Он принимает параметр в качестве первого входного сигнала для сравнения со строкой "short" – но его проще читать, если параметр идет первым.
Код шаблона определяется как:
{{#ifeq: {{{1|}}} | short | 20 | 40 }}
и работает следующим образом:
{{timer|short}}
→ 20{{timer|20}}
→ 40{{timer}}
→ 40
#iferror
Эта функция принимает входную строку и возвращает один из двух результатов; функция возвращает значение true
, если входная строка содержит HTML-объект с class="error"
, генерируемый другими функциями синтаксического анализатора, такими как #expr
, #time
и #rel2abs
, шаблоны ошибки, такие как циклы и рекурсии, и другие "отказоустойчивые" ошибки парсера.
{{#iferror: test string | value if error | value if correct }}
Одна или обе возвращаемые строки могут быть опущены. Если строка "correct"
опущена, то "test string"
возвращается, если она не ошибочна. Если строка "error"
также опущена, то при ошибке возвращается пустая строка:
{{#iferror: {{#expr: 1 + 2 }} | error | correct }}
→ correct{{#iferror: {{#expr: 1 + X }} | error | correct }}
→ error{{#iferror: {{#expr: 1 + 2 }} | error }}
→ 3{{#iferror: {{#expr: 1 + X }} | error }}
→ error{{#iferror: {{#expr: 1 + 2 }} }}
→ 3{{#iferror: {{#expr: 1 + X }} }}
→ {{#iferror: {{#expr: . }} | error | correct }}
→ correct{{#iferror: <strong class="error">a</strong> | error | correct }}
→ error
#ifexpr
Эта функция вычисляет математическое выражение и возвращает одну из двух строк в зависимости от логического значения результата:
{{#ifexpr: expression | value if true | value if false }}
Входные данные "выражение"
вычисляются точно так же, как и для #expr
выше, причем доступны те же операторы. Выходные данные затем вычисляются как логическое выражение.
Пустое входное выражение принимает значение false
:
{{#ifexpr: | yes | no}}
→ no
Как упоминалось выше, нулевое значение равно false
, а любое не нулевое значение равно true
, поэтому эта функция эквивалентна функциям #ifeq
и #expr
, использующихся одновременно:
{{#ifeq: {{#expr: expression }} | 0 | value if false | value if true }}
за исключением пустого или неправильного входного выражения (сообщение об ошибке обрабатывается как пустая строка; оно не равно нулю, поэтому мы получаем "значение, если истина"
).
{{#ifexpr: = | yes | no }}
→ Expression error: Unexpected = operator.
сравнение
{{#ifeq: {{#expr: = }} | 0 | no | yes }}
→ yes
Одно или оба возвращаемых значения могут быть опущены; если соответствующая ветвь оставлена пустой, выходные данные не выводятся.:
{{#ifexpr: 1 > 0 | yes }}
→ yes{{#ifexpr: 1 < 0 | yes }}
→{{#ifexpr: 0 = 0 | yes }}
→ yes{{#ifexpr: 1 > 0 | | no}}
→{{#ifexpr: 1 < 0 | | no}}
→ no{{#ifexpr: 1 > 0 }}
→
#ifexist
Эта функция принимает входную строку, интерпретирует ее как заголовок страницы и возвращает одно из двух значений в зависимости от того, существует ли страница в локальной Вики.
{{#ifexist: page title | value if exists | value if doesn't exist }}
Функция принимает значение истина
, если страница существует, независимо от того, содержит ли она содержимое, является ли она явно пустой (содержит метаданные, такие как ссылки на категории или Волшебные слова , но не содержит видимого содержимого), является пустой или является перенаправлением . Только страницы, имеющие красные ссылки, оцениваются как ложь
, в том числе если страница существовала, но была удалена.
{{#ifexist: Help:Extension:ParserFunctions/ru | exists | doesn't exist }}
→ exists{{#ifexist: XXHelp:Extension:ParserFunctions/ruXX | exists | doesn't exist }}
→ doesn't exist
Функция возвращает значение истина
для системных сообщений , которые были настроены, и для специальных страниц , которые определены программным обеспечением.
{{#ifexist: Special:Watchlist | exists | doesn't exist }}
→ exists{{#ifexist: Special:CheckUser | exists | doesn't exist }}
→ exists (потому что расширение Checkuser установлено на этой вики-странице){{#ifexist: MediaWiki:Copyright | exists | doesn't exist }}
→ exists (потому что MediaWiki:Copyright был настроен)
Если страница проверяет цель с помощью #ifexist:
, то эта страница появится в списке Special:WhatLinksHere для целевой страницы. Поэтому, если код {{#ifexist:Foo }}
был включен на этой странице (Help:Extension:ParserFunctions/ru), Special:WhatLinksHere/Foo будет содержать Help:Extension:ParserFunctions/ru.
В вики, использующих общий медиа-репозиторий, #ifexist:
можно использовать для проверки, был ли файл загружен в репозиторий, но не в саму Вики:
{{#ifexist: File:Example.png | exists | doesn't exist }}
→ doesn't exist{{#ifexist: Image:Example.png | exists | doesn't exist }}
→ doesn't exist{{#ifexist: Media:Example.png | exists | doesn't exist }}
→ exists
Если для файла была создана локальная страница описания, результатом будет "существуют" для всех вышеперечисленных.
#ifexist:
не работает с интервики-ссылками.
#ifexist ограничения
#ifexist:
считается "дорогой функцией парсера"; только ограниченное число может быть включено на каждой отдельной странице (включая функции внутри трансклюзованных шаблонов). При превышении этого предела любые дополнительные функции #ifexist:
автоматически возвращают Ложь, независимо от того, существует ли целевая страница или нет, и страница классифицируется в Category:Pages with too many expensive parser function calls. Название категории может варьировать в зависимости от языка содержимого Вики.
В некоторых случаях можно эмулировать эффект #ifexist с помощью css, используя селекторы a.new
(для выбора ссылок на несуществующие страницы) или a:not(.new)
(для выбора ссылок на существующие страницы). Кроме того, поскольку количество данных функций парсера, которые могут быть использованы на одной странице, контролируется $wgExpensiveParserFunctionLimit
, можно также увеличить лимит в LocalSettings.php, если нужно.
#ifexist и разыскиваемые страницы
Страница, которая не существует и проверена на использование #ifexist, будет в конечном итоге на Разыскиваемые страницы.
#rel2abs
Эта функция преобразует относительный путь к файлу в абсолютный путь к файлу.
{{#rel2abs: path }}
{{#rel2abs: path | base path }}
Во входных данных path
допустим следующий синтаксис:
.
→ текущий уровень..
→ подняться на один уровень вверх/foo
→ опустится на один уровень вниз в подкаталог /foo
Если base path
не указан, вместо него будет использоваться полное имя страницы:
{{#rel2abs: /quok | Help:Foo/bar/baz }}
→ Help:Foo/bar/baz/quok{{#rel2abs: ./quok | Help:Foo/bar/baz }}
→ Help:Foo/bar/baz/quok{{#rel2abs: ../quok | Help:Foo/bar/baz }}
→ Help:Foo/bar/quok{{#rel2abs: ../. | Help:Foo/bar/baz }}
→ Help:Foo/bar
Недопустимый синтаксис, например /.
или /./
, игнорируются.
Поскольку допускается не более двух последовательных полных остановок, такие последовательности могут использоваться для разделения последовательных операторов:
{{#rel2abs: ../quok/. | Help:Foo/bar/baz }}
→ Help:Foo/bar/quok{{#rel2abs: ../../quok | Help:Foo/bar/baz }}
→ Help:Foo/quok{{#rel2abs: ../../../quok | Help:Foo/bar/baz }}
→ quok{{#rel2abs: ../../../../quok | Help:Foo/bar/baz }}
→ Error: Invalid depth in path: "Help:Foo/bar/baz/../../../../quok" (tried to access a node above the root node).
#switch
See also : w:Help:Switch parser function
Эта функция сравнивает одно входное значение с каждым из набора заранее указанных вариантов, возвращая соответствующую совпавшему варианту строку, если совпадение найдено.
{{#switch: comparison string | case = result | case = result | ... | case = result | default result }}
Примеры:
{{#switch: baz | foo = Foo | baz = Baz | Bar }}
→ Baz{{#switch: foo | foo = Foo | baz = Baz | Bar }}
→ Foo{{#switch: zzz | foo = Foo | baz = Baz | Bar }}
→ Bar
#switch с тегами частичной трансклюзии может создавать конфигурационный файл, который позволяет редактору, незнакомому с шаблонным кодированием, просматривать и редактировать настраиваемые элементы.
По умолчанию
"результат по умолчанию"
возвращается, если строка "случай"
не совпадает с "строка сравнения"
:
{{#switch: test | foo = Foo | baz = Baz | Bar }}
→ Bar
В этом синтаксисе результат по умолчанию должен быть последним параметром и не должен содержать обычный (необработанный) знак равенства (знак равенства без {{}}
).
Если это так, он будет рассматриваться как сравнение случаев, и текст не будет отображаться, если ни один случай не совпадает.
Это потому, что значение по умолчанию не было определено (является пустым).
Однако, если регистр совпадает, будет возвращена связанная с ним строка.
{{#switch: test | Bar | foo = Foo | baz = Baz }}
→{{#switch: test | foo = Foo | baz = Baz | B=ar }}
→{{#switch: test | test = Foo | baz = Baz | B=ar }}
→ Foo
Кроме того, результат по умолчанию может быть явно объявлен с "случай"
строкой "#default
".
{{#switch: comparison string | case = result | case = result | ... | case = result | #default = default result }}
Результаты по умолчанию, объявленные таким образом, могут быть размещены в любом месте функции:
{{#switch: test | foo = Foo | #default = Bar | baz = Baz }}
→ Bar
Если параметр "default"
опущен и не выполняется сопоставление, то "result"
не возвращается:
{{#switch: test | foo = Foo | baz = Baz }}
→
Группировка результатов
Возможен 'провал' значения, где "случай"
строки возвращают одинаковые "результат"
строки. Это сводит к минимуму дублирование.
{{#switch: comparison string | case1 = result1 | case2 | case3 | case4 = result234 | case5 = result5 | case6 | case7 = result67 | #default = default result }}
Здесь случаи 2, 3 и 4 возвращают "результат234"
; случаи 6 и 7 оба возвращают "результат67"
"#default =
" в последнем параметре может быть опущено в вышеупомянутом случае.
Использование с параметрами
Функция может использоваться с параметрами в виде тестовой строки.
In this case, it is not necessary to place the pipe after the parameter name, because it is very unlikely that you will choose to set a case to be the string "{{{parameter name}}}
".
(This is the value the parameter will default to if the pipe is absent and the parameter doesn't exist or have a value.
Смотрите Справка:Функции парсера в шаблонах .)
{{#switch: {{{1}}} | foo = Foo | baz = Baz | Bar }}
In the above case, if {{{1}}}
equals foo
, the function will return Foo
.
If it equals baz
, the function will return Baz
.
If the parameter is empty or does not exist, the function will return Bar
.
As in the section above, cases can be combined to give a single result.
{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | Bar }}
Here, if {{{1}}}
equals foo
, zoo
or roo
, the function will return Foo
.
If it equals baz
, the function will return Baz
.
If the parameter is empty or does not exist, the function will return Bar
.
Additionally, the default result can be omitted if you do not wish to return anything if the test parameter value does not match any of the cases.
{{#switch: {{{1}}} | foo = Foo | bar = Bar }}
In this case, the function returns an empty string unless {{{1}}}
exists and equals foo
or bar
, in which case it returns Foo
or Bar
, respectively.
This has the same effect as declaring the default result as empty.
{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | }}
If for some reason you decide to set a case as "{{{parameter name}}}
", the function will return that case's result when the parameter doesn't exist or doesn't have a value.
The parameter would have to exist and have a value other than the string "{{{parameter name}}}
" to return the function's default result.
- (when
{{{1}}}
doesn't exist or is empty):{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }}
→ Foo
- (when
{{{1}}}
has the value "test
"):{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }}
→ Bar
- (when
{{{1}}}
has the value "{{{1}}}
"):{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }}
→ Foo
In this hypothetical case, you would need to add the pipe to the parameter ({{{1|}}}
).
Поведение сравнения
Как и в случае с #ifeq
, сравнение производится численно, если и строка сравнения, и проверяемая строка регистра являются числовыми; или как чувствительная к регистру строка в противном случае:
{{#switch: 0 + 1 | 1 = one | 2 = two | three}}
→ three{{#switch: {{#expr: 0 + 1}} | 1 = one | 2 = two | three}}
→ one
{{#switch: a | a = A | b = B | C}}
→ A{{#switch: A | a = A | b = B | C}}
→ C
Строка "случай"
может быть пустой:
{{#switch: | = Nothing | foo = Foo | Something }}
→ Nothing
Как только совпадение найдено, последующие "случаи"
игнорируются:
{{#switch: b | f = Foo | b = Bar | b = Baz | }}
→ Bar
Необработанные знаки равенства
Строки "Случай" не могут содержать необработанные знаки равенства. Чтобы обойти это, создайте шаблон {{=}}, содержащий один знак равенства: =
, или замените знак равенства html-кодом =
.
Пример:
{{#switch: 1=2
| 1=2 = raw
| 1<nowiki>=</nowiki>2 = nowiki
| 1{{=}}2 = template
| default
}}
→ template
{{#switch: 1=2
| 1=2 = html
| default
}}
→ html
Замена #ifeq
#switch
не может быть использован, чтобы уменьшить глубину расширения.
Например:
{{#switch:{{{1}}} |condition1=branch1 |condition2=branch2 |condition3=branch3 |branch4}}
эквивалентно
{{#ifeq:{{{1}}}|condition1 |branch1 |{{#ifeq:{{{1}}}|condition2 |branch2 |{{#ifeq:{{{1}}}|condition3 |branch3 |branch4}}}}}}
т.е. глубокая вложенность, линейная:
{{#ifeq:{{{1}}}|condition1
|<!--then-->branch1
|<!--else-->{{#ifeq:{{{1}}}|condition2
|<!--then-->branch2
|<!--else-->{{#ifeq:{{{1}}}|condition3
|<!--then-->branch3
|<!--else-->branch4}}}}}}
С другой стороны, замена переключателя может быть сложной/непрактичной для #if, вложенных в обе ветви (показано с альтернативами отступа, отступами с обеих сторон), что делает полное симметричное дерево:
{{#ifeq:{{{1}}}|condition1
|<!--then-->branch1t{{
#ifeq:{{{1}}}|condition2
|<!--then-->branch1t2t{{#ifeq:{{{1}}}|condition4|<!--then-->branch1t2t4t|<!--else-->branch1t2t4e}}
|<!--else-->branch1t2e{{#ifeq:{{{1}}}|condition5|<!--then-->branch1t2e5t|<!--else-->branch1t2e5e}}
}}
|<!--else-->branch1e{{#ifeq:{{{1}}}|condition3
|<!--then-->branch1e3t{{#ifeq:{{{1}}}|condition6|branch1e3t6t|branch1e3t6e}}
|<!--else-->branch1e3e{{
#ifeq:{{{1}}}|condition7
|branch1e3e7t
|branch1e3e7t
}}
}}
}}
#time
Код | Описание | Текущий вывод (очистить кэш этой страницы для обновления) |
---|---|---|
Год | ||
Y
|
4-х значный год. | 2021 |
y
|
2-х значный год. | 21 |
L
|
1, если это високосный год, 0, если нет. | 0 |
o [note 1]
|
ISO-8601 год указанной недели.[note 2] | 2021[note 3] |
| ||
Месяц | ||
n
|
Индекс месяца, без нуля. | 4 |
m
|
Индекс месяца, с нулем. | 04 |
M
|
Аббревиатура названия месяца на языке сайта. | апр |
F
|
Полное название месяца на языке сайта. | апрель |
xg
|
Выведит полное название месяца в родительном падеже для языков сайта, которые различают родительный падеж и именительный падеж. Эта опция полезна для многих славянских языков, таких как польский, русский, белорусский, чешский, словацкий, словенский, украинский и т. д. | Для Польского:{{#time:F Y|June 2010|pl}} → czerwiec 2010(именительный падеж) {{#time:d xg Y|20 June 2010|pl}} → 20 czerwca 2010(родительный падеж) |
День месяца или года | ||
j
|
День месяца, без нуля. | 18 |
d
|
День месяца, с нулём. | 18 |
z
|
День года (январь 1 = 0).в ![]() |
107 |
Неделя и день недели | ||
W
|
ISO 8601 номер недели, c нулём. | 15 |
N
|
ISO 8601 номер дня недели (понедельник = 1, воскресенье = 7). | 7 |
w
|
Номер дня недели (воскресенье = 0, суббота = 6). | 0 |
D
|
Аббревиатура дня недели. Редко интернационализируется. | Вс |
l
|
Полное название дня недели. Редко интернационализируется. | воскресенье |
Час | ||
a
|
"am" время до обеда (00:00:00 → 11:59:59), "pm" время после обеда (12:00:00 → 23:59:59). | pm |
A
|
Прописная версия a выше.
|
PM |
g
|
Час в 12-часовом формате, без нуля. | 6 |
h
|
Час в 12-часовом формате, с ведущим нулём. | 06 |
G
|
Час в 24-часовом формате, без ведущего нуля. | 18 |
H
|
Час в 24-часовом формате, с ведущим нулём. | 18 |
Минуты и секунды | ||
i
|
Минуты без указания часа с нулём. | 26 |
s
|
Секунды без указания минуты с нулем. | 10 |
U
|
UNIX-время. Секунды, прошедшие с 1 января 1970 00:00:00 GMT. | 1618770370 |
Часовой пояс (как и 1.22wmf2) | ||
e
|
Идентификатор часового пояса. | UTC |
I
|
Независимо от того, находится ли эта дата в летнее время или нет. | 0 |
O
|
Разница с временем Гринвича (GMT) | +0000 |
P
|
Разница с временем Гринвича (GMT) с двоеточием | +00:00 |
T
|
Аббревиатура часового пояса. | UTC |
Z
|
Смещение часового пояса в секундах. | 0 |
Разное | ||
t
|
Количество дней в текущем месяце. | 30 |
c
|
Дата, форматированная по ISO 8601, эквивалент Y-m-d"T"H:i:s+00:00
|
2021-04-18T18:26:10+00:00 |
r
|
Дата, форматированная по RFC 5322, эквивалент D, j M Y H:i:s +0000 . Названия дней недель и месяцев не переведены.
|
Sun, 18 Apr 2021 18:26:10 +0000 |
Не Григорианские календари | ||
Исламский | ||
xmj
|
День месяца. | 6 |
xmF
|
Полное название месяца. | Рамадан |
xmn
|
Номер месяца. | 9 |
xmY
|
Год полностью. | 1442 |
Иранский (Джалали) | ||
xit
|
Количество дней в текущем месяце. | 31 |
xiz
|
День года. | 28 |
xij
|
День месяца. | 29 |
xiF
|
Полное название месяца. | Фарвардин |
xin
|
Номер месяца. | 1 |
xiY
|
Год полностью. | 1400 |
xiy
|
2-х значный год. | 00 |
Еврейский | ||
xjj
|
День месяца. | 6 |
xjF
|
Полное название месяца. | Ияр |
xjt
|
Количество дней в текущем месяце. | 29 |
xjx
|
Название месяца в родительном падеже. | Ияра |
xjn
|
Номер месяца. | 8 |
xjY
|
Год полностью. | 5781 |
Тайский солнечный | ||
xkY
|
Full year in Thai solar calendar. ![]() |
2564 |
Год Минго/Чучхе | ||
xoY
|
Год полностью. | 110 |
Японская система нэнго | ||
xtY
|
Год полностью. | 令和3 |
Флаги | ||
xn
|
Format the next numeric code as a raw ASCII number. | In the Hindi language, {{#time:H, xnH}} produces ०६, 06.
|
xN
|
Подобен xn , но работает как переключатель: действует до конца строки или до следующего появления xN в строке.
| |
xr
|
Форматирует следующее число как римское. Работает только для чисел до 10 000 (до 3,000 в MediaWiki до 1.20). |
{{#time:xrY}} → MMXXI
|
xh
|
Format the next number as a Hebrew numeral. | {{#time:xhY}} → ב'כ"א
|
Эта функция парсера берет дату и/или время (по Григорианскому календарю) и форматирует ее в соответствии с заданным синтаксисом. Можно задать объект даты/времени; для этого, по умолчанию используется значение волшебного слова {{CURRENTTIMESTAMP}}
– то есть время, когда страница была в последний раз отображена в HTML.
{{#time: format string }}
{{#time: format string | date/time object }}
{{#time: format string | date/time object | language code }}
{{#time: format string | date/time object | language code | local }}
Список принятых кодов форматирования приведен в таблице справа. Любой не распознаваемый символ в строке форматирования передается как неизменённый; это относится также к пустым местам (система не нуждается в них для интерпретации кодов). Существует также два способа экранирования символов в строке форматирования:
- Обратная косая черта, за которой следует символ форматирования, интерпретируется как один литеральный символ
- Символы, заключенные в двойные кавычки, считаются литеральными символами, и кавычки удаляются.
Кроме того, орграф xx
интерпретируется как один литерал "x".
{{#time: Y-m-d }}
→ 2021-04-18{{#time: [[Y]] m d }}
→ 2021 04 18{{#time: [[Y (year)]] }}
→ 2021 (21UTCpmSun, 18 Apr 2021 18:26:10 +0000){{#time: [[Y "(year)"]] }}
→ 2021 (year){{#time: i's" }}
→ 26'10"
The date/time object
can be in any format accepted by PHP's strtotime() function. Both absolute (eg 20 December 2000
) and relative (eg +20 hours
) times are accepted.
{{#time: r|now}}
→ Sun, 18 Apr 2021 18:26:10 +0000{{#time: r|+2 hours}}
→ Sun, 18 Apr 2021 20:26:10 +0000{{#time: r|now + 2 hours}}
→ Sun, 18 Apr 2021 20:26:10 +0000{{#time: r|20 December 2000}}
→ Wed, 20 Dec 2000 00:00:00 +0000{{#time: r|December 20, 2000}}
→ Wed, 20 Dec 2000 00:00:00 +0000{{#time: r|2000-12-20}}
→ Wed, 20 Dec 2000 00:00:00 +0000{{#time: r|2000 December 20}}
→ Error: Invalid time.
The language code
in ISO 639-3 (?) allows the string to be displayed in the chosen language
{{#time:d F Y|1988-02-28|nl}}
→ 28 februari 1988{{#time:l|now|uk}}
→ неділя{{#time:d xg Y|20 June 2010|pl}}
→ 20 czerwca 2010
The local
parameter specifies if the date/time object refers to the local timezone or to UTC.
This is a boolean parameters: its value is determined by casting the value of the argument (see the official PHP documentation for details on how string are cast to boolean values).
$wgLocaltimezone
is set to UTC
, there is no difference in the output when local
is set to true
or false
.See the following examples for details:
{{#time: Y F d H:i:s|now|it|0}}
→ 2021 aprile 18 18:26:10{{#time: Y F d H:i:s|now|it|1}}
→ 2021 aprile 18 18:26:11{{#time: Y F d H:i:s|+2 hours||0}}
→ 2021 апрель 18 20:26:11{{#time: Y F d H:i:s|+2 hours||1}}
→ 2021 апрель 18 20:26:11
{{#time:c|2019-05-16T17:05:43+02:00|it}}
→ 2019-05-16T15:05:43+00:00{{#time:c|2019-05-16T17:05:43+02:00|it|0}}
→ 2019-05-16T15:05:43+00:00{{#time:c|2019-05-16T17:05:43+02:00|it|true}}
→ 2019-05-16T15:05:43+00:00
If you've calculated a Unix timestamp, you may use it in date calculations by pre-pending an @
symbol.
{{#time: U | now }}
→ 1618770371{{#time: r | @1618770370 }}
→ Sun, 18 Apr 2021 18:26:10 +0000
Full or partial absolute dates can be specified; the function will "fill in" parts of the date that are not specified using the current values:
{{#time: Y | January 1 }}
→ 2021
A four-digit number is always interpreted as a year, never as hours and minutes:[1]
{{#time: Y m d H:i:s | 1959 }}
→ 1959 04 18 00:00:00
A six-digit number is interpreted as hours, minutes and seconds if possible, but otherwise as an error (not, for instance, a year and month):
{{#time: Y m d H:i:s | 195909 }}
→ 2021 04 18 19:59:09 Input is treated as a time rather than a year+month code.{{#time: Y m d H:i:s | 196009 }}
→ Error: Invalid time. Although 19:60:09 is not a valid time, 196009 is not interpreted as September 1960.
The function performs a certain amount of date mathematics:
{{#time: d F Y | January 0 2008 }}
→ 31 декабрь 2007{{#time: d F | January 32 }}
→ Error: Invalid time.{{#time: d F | February 29 2008 }}
→ 29 февраль{{#time: d F | February 29 2007 }}
→ 01 март{{#time:Y-F|now -1 months}}
→ 2021-март
The total length of the format strings of the calls of #time
is limited to 6000 characters[2].
Вопрос часового пояса
В функции #time parser существует ошибка(более конкретно в "PHP DateTime"), которая не позволяет передавать "нецелые числа" в качестве относительных смещений часовых поясов. Эта проблема не касается использования часового пояса, например EDT. Например:
{{#time:g:i A | -4 hours }}
→ 2:26 PM
Однако, Индия находится на смещении времени +5,5 часа от UTC, и поэтому использование ее часового пояса обычно не позволяет правильно рассчитать относительное смещение часового пояса. Вот что происходит:
{{#time:g:i A | +5.5 hours }}
→ 6:26 PM
Чтобы обойти эту проблему, просто преобразуйте время в минуты или секунды, например:
{{#time:g:i A | +330 minutes }}
→ 11:56 PM{{#time:g:i A | +19800 seconds }}
→ 11:56 PM
(Тим Старлинг, разработчик этой функции, предоставил точный синтаксис для его решения.)
#timel
Эта функция полностью идентична функции {{#time: ... }}
в том случае, если параметр local
настроен как true
. При этом всегда используется местное время, установленное в вашей вики при настройке $wgLocaltimezone .
Синтаксис функции следующий:
{{#timel: format string }}
{{#timel: format string | date/time object }}
{{#timel: format string | date/time object | language code }}
$wgLocaltimezone
настроена как UTC
, то нет никакой разницы, настроен ли local
как true
или как false
, т. к. на выходе будет один и тот же результат.For instance, see the following examples:
{{#time:c|now|it}}
→ 2021-04-18T18:26:11+00:00{{#time:c|now|it|0}}
→ 2021-04-18T18:26:11+00:00{{#time:c|now|it|1}}
→ 2021-04-18T18:26:11+00:00{{#timel:c|now|it}}
→ 2021-04-18T18:26:11+00:00

#titleparts
Эта функция разделяет заголовок страницы на сегменты, разделённые слэшем ("/"), и затем на выходе возвращает некоторые из этих сегментов.
{{#titleparts: имя страницы | количество выводимых сегментов | номер первого выводимого сегмента }}
Если параметр количество выводимых сегментов не определён, он принимается равным нулю ("0"), и выводятся все сегменты начиная с номера первого выводимого сегмента (включительно). Если номер первого выводимого сегмента не определён или равен "0", то он принимает значение по умолчанию "1":
{{#titleparts: Talk:Foo/bar/baz/quok }}
→ Talk:Foo/bar/baz/quok{{#titleparts: Talk:Foo/bar/baz/quok | 1 }}
→ Talk:Foo See also {{ROOTPAGENAME }}.{{#titleparts: Talk:Foo/bar/baz/quok | 2 }}
→ Talk:Foo/bar{{#titleparts: Talk:Foo/bar/baz/quok | 2 | 2 }}
→ bar/baz{{#titleparts: Talk:Foo/bar/baz/quok | | 2 }}
→ bar/baz/quok{{#titleparts: Talk:Foo/bar/baz/quok | | 5 }}
→
Negative values are accepted for both values. Negative values for the number of segments to return parameter effectively 'strips' segments from the end of the string. Negative values for the first segment to return translates to "start with this segment counting from the right":
{{#titleparts: Talk:Foo/bar/baz/quok | -1 }}
→ Talk:Foo/bar/baz Strips one segment from the end of the string. См. также {{BASEPAGENAME}}.{{#titleparts: Talk:Foo/bar/baz/quok | -4 }}
→ Strips all 4 segments from the end of the string{{#titleparts: Talk:Foo/bar/baz/quok | -5 }}
→ Strips 5 segments from the end of the string (more than exist){{#titleparts: Talk:Foo/bar/baz/quok | | -1 }}
→ quok Returns last segment. См. также {{SUBPAGENAME}}.{{#titleparts: Talk:Foo/bar/baz/quok | -1 | 2 }}
→ bar/baz Strips one segment from the end of the string, then returns the second segment and beyond{{#titleparts: Talk:Foo/bar/baz/quok | -1 | -2 }}
→ baz Start copying at the second last element; strip one segment from the end of the string
Before processing, the pagename parameter is HTML-decoded: if it contains some standard HTML character entities, they will be converted to plain characters (internally encoded with UTF-8, i.e. the same encoding as in the MediaWiki source page using this parser function).
- For example, any occurrence of
"
,"
, or"
in pagename will be replaced by"
. - No other conversion from HTML to plain text is performed, so HTML tags are left intact at this initial step even if they are invalid in page titles.
Some magic keywords or parser functions of MediaWiki (such as {{PAGENAME }}
and similar) are known to return strings that are needlessly HTML-encoded, even if their own input parameter was not HTML-encoded:
The titleparts parser function can then be used as a workaround, to convert these returned strings so that they can be processed correctly by some other parser functions also taking a page name in parameter (such as {{PAGESINCAT: }}
but which are still not working properly with HTML-encoded input strings.
For example, if the current page is Category:Côte-d'Or, then:
{{#ifeq: {{FULLPAGENAME}} | Category:Côte-d'Or | 1 | 0 }}
, and{{#ifeq: {{FULLPAGENAME}} | Category:Côte-d'Or | 1 | 0 }}
are both returning1
; (the #ifeq parser function does perform the HTML-decoding of its input parameters).{{#switch: {{FULLPAGENAME}} | Category:Côte-d'Or = 1 | #default = 0 }}
, and{{#switch: {{FULLPAGENAME}} | Category:Côte-d'Or = 1 | #default = 0 }}
are both returning1
; (the #switch parser function does perform the HTML-decoding of its input parameters).{{#ifexist: {{FULLPAGENAME}} | 1 | 0 }}
,{{#ifexist: Category:Côte-d'Or | 1 | 0 }}
, or even{{#ifexist: Category:Côte-d'Or | 1 | 0 }}
will all return1
if that category page exists (the #ifexist parser function does perform the HTML-decoding of its input parameters);{{PAGESINCAT: Côte-d'Or }}
will return a non-zero number, if that category contains pages or subcategories, but:{{PAGESINCAT: {{CURRENTPAGENAME}} }}
, may still unconditionally return 0, just like:{{PAGESINCAT: {{PAGENAME|Category:Côte-d'Or}} }}
{{PAGESINCAT: {{PAGENAME|Category:Côte-d'Or}} }}
The reason of this unexpected behavior is that, with the current versions of MediaWiki, there are two caveats:
{{FULLPAGENAME}}
, or even{{FULLPAGENAME|Côte-d'Or}}
may return the actually HTML-encoded stringCategory:Côte-d'Or
and not the expectedCategory:Côte-d'Or
, and that:{{PAGESINCAT: Côte-d'Or }}
unconditionally returns 0 (the PAGESINCAT magic keyword does not perform any HTML-decoding of its input parameter).
The simple workaround using titleparts (which will continue to work if the two caveats are fixed in a later version of MediaWiki) is:
{{PAGESINCAT: {{#titleparts: {{CURRENTPAGENAME}} }} }}
{{PAGESINCAT: {{#titleparts: {{PAGENAME|Category:Côte-d'Or}} }} }}
{{PAGESINCAT: {{#titleparts: {{PAGENAME|Category:Côte-d'Or}} }} }}
, that all return the actual number of pages in the same category.
Then the decoded pagename is canonicalized into a standard page title supported by MediaWiki, as much as possible:
- All underscores are automatically replaced with spaces:
{{#titleparts: Talk:Foo/bah_boo|1|2}}
→ bah boo Not bah_boo, despite the underscore in the original.
- The string is split a maximum of 25 times; further slashes are ignored and the 25th element will contain the rest of the string. The string is also limited to 255 characters, as it is treated as a page title:
{{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee | 1 | 25 }}
→ y/z/aa/bb/cc/dd/ee- If for whatever reason you needed to push this function to its limit, although very unlikely, it is possible to bypass the 25 split limit by nesting function calls:
{{#titleparts: {{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee| 1 | 25 }} | 1 | 2}}
→ z
- Finally the first substring is capitalized according to the capitalization settings of the local wiki (if that substring also starts by a local namespace name, that namespace name is also normalized).
{{#titleparts: talk:a/b/c }}
→ Talk:A/b/c
Строковые функции
All of these functions (len
, pos
, rpos
, sub
, replace
, explode
) are integrated from the StringFunctions extension, but are only available if an administrator sets $wgPFEnableStringFunctions = true;
in LocalSettings.php
.
All of these functions operate in O(n) time complexity, making them safe against DoS attacks.
- Some parameters of these functions are limited through global settings to prevent abuse.
- For functions that are case sensitive, you may use the magic word
{{lc:string}}
as a workaround in some cases.
- To determine whether a MediaWiki server enables these functions, check the list of supported Extended parser functions in Special:Version.
- String length is limited by
$wgPFStringLengthLimit
variable, default to 1000.
#len
#len
parser function was merged from the StringFunctions extension as of version 1.2.0.The #len function returns the length of the given string. The syntax is:
{{#len:string}}
The return value is always a number of characters in the source string (after expansions of template invocations, but before conversion to HTML). If no string is specified, the return value is zero.
- This function is safe with UTF-8 multibyte characters.
{{#len:Žmržlina}}
→8
- Leading and trailing spaces or newlines are not counted, but intermediate spaces and newlines are taken into account.
{{#len:Icecream }}
→8
{{#len: a b }}
→5
- 3 пробела между 2 символами
- Characters given by reference are not converted, but counted according to their source form.
{{#len: }}
→6
- named characters references{{#len: }}
→5
- numeric characters references, not ignored despite it designates a space here.
- Tags such as
<nowiki>
and other tag extensions will always have a length of zero, since their content is hidden from the parser.
{{#len:<nowiki>This is a </nowiki>test}}
→4
#pos
#pos
parser function was merged from the StringFunctions extension as of version 1.2.0.The #pos function returns the position of a given search term within the string. The syntax is:
{{#pos:string|search term|offset}}
The offset parameter, if specified, tells a starting position where this function should begin searching.
If the search term is found, the return value is a zero-based integer of the first position within the string.
If the search term is not found, the function returns an empty string.
- This function is case sensitive.
- The maximum allowed length of the search term is limited through the $wgStringFunctionsLimitSearch global setting.
- This function is safe with UTF-8 multibyte characters.
{{#pos:Žmržlina|žlina}}
returns 3.
- As with #len,
<nowiki>
and other tag extensions are treated as having a length of 1 for the purposes of character position.
{{#pos:<nowiki>This is a </nowiki>test|test}}
returns 1.#rpos
#rpos
parser function was merged from the StringFunctions extension as of version 1.2.0.The #rpos function returns the last position of a given search term within the string. The syntax is:
{{#rpos:string|search term}}
If the search term is found, the return value is a zero-based integer of its last position within the string.
If the search term is not found, the function returns -1.
- This function is case sensitive.
- The maximum allowed length of the search term is limited through the $wgStringFunctionsLimitSearch global setting.
- This function is safe with UTF-8 multibyte characters.
{{#rpos:Žmržlina|lina}}
returns 4.
- As with #len,
<nowiki>
and other tag extensions are treated as having a length of 1 for the purposes of character position.
{{#rpos:<nowiki>This is a </nowiki>test|test}}
returns 1.#sub
#sub
parser function was merged from the StringFunctions extension as of version 1.2.0.The #sub function returns a substring from the given string. The syntax is:
{{#sub:string|start|length}}
The start parameter, if positive (or zero), specifies a zero-based index of the first character to be returned.
Пример:
{{#sub:Icecream|3}}
returns cream
.
{{#sub:Icecream|0|3}}
returns Ice
.
If the start parameter is negative, it specifies how many characters from the end should be returned.
Пример:
{{#sub:Icecream|-3}}
returns eam
.
The length parameter, if present and positive, specifies the maximum length of the returned string.
Пример:
{{#sub:Icecream|3|3}}
returns cre
.
If the length parameter is negative, it specifies how many characters will be omitted from the end of the string.
Пример:
{{#sub:Icecream|3|-3}}
returns cr
.
If the start parameter is negative, it specifies how many characters from the end should be returned. The length parameter, if present and positive, specifies the maximum length of the returned string from the starting point.
Пример:
{{#sub:Icecream|-3|2}}
returns ea
.
- If the length parameter is zero, it is not used for truncation at all.
- Пример:
{{#sub:Icecream|3|0}}
returnscream
.{{#sub:Icecream|0|3}}
returnsIce
.
- Пример:
- If start denotes a position beyond the truncation from the end by negative length parameter, an empty string will be returned.
- Пример:
{{#sub:Icecream|3|-6}}
returns an empty string.
- Пример:
- This function is safe with UTF-8 multibyte characters.
{{#sub:Žmržlina|3}}
returns žlina
.
- As with #len,
<nowiki>
and other tag extensions are treated as having a length of 1 for the purposes of character position.
{{#sub:<nowiki>This is a </nowiki>test|1}}
returns test
.#replace
#replace
parser function was merged from the StringFunctions extension as of version 1.2.0.The #replace function returns the given string with all occurrences of a search term replaced with a replacement term.
{{#replace:string|search term|replacement term}}
If the search term is unspecified or empty, a single space will be searched for.
If the replacement term is unspecified or empty, all occurrences of the search term will be removed from the string.
- This function is case-sensitive.
- The maximum allowed length of the search term is limited through the $wgStringFunctionsLimitSearch global setting.
- The maximum allowed length of the replacement term is limited through the $wgStringFunctionsLimitReplace global setting.
- Even if the replacement term is a space, an empty string is used.
- Пример:
{{#replace:My_little_home_page|_|<nowiki> </nowiki>}}
returnsMy little home page
.
- Пример:
- If this doesn't work, try
{{#replace:My_little_home_page|_|<nowiki/> <nowiki/>}}
with two self-closing tags.
- If this doesn't work, try
- Note that this is the only acceptable use of nowiki in the replacement term, as otherwise nowiki could be used to bypass $wgStringFunctionsLimitReplace, injecting an arbitrarily large number of characters into the output.
<nowiki>
or any other tag extension within the replacement term are replaced with spaces.
- This function is safe with UTF-8 multibyte characters.
{{#replace:Žmržlina|ž|z}}
returns Žmrzlina
.
- If multiple items in a single text string need to be replaced, one could also consider Extension:ReplaceSet .
- Case-insensitive replace
Currently the syntax doesn't provide a switch to toggle case-sensitivity setting. But you may make use of magic words of formatting as a workaround. (e.g. {{lc:your_string_here}}) For example, if you want to remove the word "Category:" from the string regardless of its case, you may type:
{{#replace:{{lc:{{{1}}}}}|category:|}}
But the disadvantage is that the output will become all lower-case. If you want to keep the casing after replacement, you have to use multiple nesting levels (i.e. multiple replace calls) to achieve the same thing.
#explode
#explode
parser function was merged from the StringFunctions extension as of version 1.2.0.The #explode function splits the given string into pieces and then returns one of the pieces. The syntax is:
{{#explode:string|delimiter|position|limit}}
The delimiter parameter specifies a string to be used to divide the string into pieces. This delimiter string is then not part of any piece, and when two delimiter strings are next to each other, they create an empty piece between them. If this parameter is not specified, a single space is used. The limit parameter is available in ParserFunctions only, not the standalone StringFunctions version, and allows you to limit the number of parts returned, with all remaining text included in the final part.
The position parameter specifies which piece is to be returned. Pieces are counted from 0. If this parameter is not specified, the first piece is used (piece with number 0). When a negative value is used as position, the pieces are counted from the end. In this case, piece number -1 means the last piece. Examples:
{{#explode:And if you tolerate this| |2}}
returnsyou
{{#explode:String/Functions/Code|/|-1}}
returnsCode
{{#explode:Split%By%Percentage%Signs|%|2}}
returnsPercentage
{{#explode:And if you tolerate this| |2|3}}
returnsyou tolerate this
The return value is the position-th piece. If there are fewer pieces than the position specifies, an empty string is returned.
- This function is case sensitive.
- The maximum allowed length of the delimiter is limited through $wgStringFunctionsLimitSearch global setting.
- This function is safe with UTF-8 multibyte characters. Example:
{{#explode:Žmržlina|ž|1}}
returnslina
.
#urldecode
#urldecode
converts the escape characters from an 'URL encoded' string string back to readable text. The syntax is:
{{#urldecode:value}}
Notes:
- This function works by directly exposing PHP's urldecode() function.
- A character-code-reference can be found at www.w3schools.com.
- The opposite,
urlencode
, has been integrated into MediaWiki as of version 1.18; for examples, see Help:Magic Words . - urldecode was merged from Stringfunctions in 2010, by commit 1b75afd18d3695bdb6ffbfccd0e4aec064785363
Limits
This module defines three global settings:
These are used to limit some parameters of some functions to ensure the functions operate in O(n) time complexity, and are therefore safe against DoS attacks.
$wgStringFunctionsLimitSearch
This setting is used by #pos, #rpos, #replace, and #explode. All these functions search for a substring in a larger string while they operate, which can run in O(n*m) and therefore make the software more vulnerable to DoS attacks. By setting this value to a specific small number, the time complexity is decreased to O(n).
This setting limits the maximum allowed length of the string being searched for.
The default value is 30 multibyte characters.
$wgStringFunctionsLimitReplace
This setting is used by #replace. This function replaces all occurrences of one string for another, which can be used to quickly generate very large amounts of data, and therefore makes the software more vulnerable to DoS attacks. This setting limits the maximum allowed length of the replacing string.
The default value is 30 multibyte characters.
Общие вопросы
Подстановка
Parser functions can be substituted by prefixing the hash character with subst:
:
{{subst:#ifexist: Help:Extension:ParserFunctions/ru | [[Help:Extension:ParserFunctions/ru]] | Help:Extension:ParserFunctions/ru }}
→ the code[[Help:Extension:ParserFunctions/ru]]
will be inserted in the wikitext since the page Help:Extension:ParserFunctions/ru exists.
Substitution does not work within <ref>
…</ref>
; you can use {{subst:#tag:ref|
…}}
for this purpose.
Перенаправления
Особенно {{#time:
…|now-
…}} может быть полезен в перенаправлении для страниц, содержащих даты, но это не всегда работает.
Экранирование символа | в таблицах
Parser functions will mangle wikitable syntax and pipe characters (|
), treating all the raw pipe characters as parameter dividers. To avoid this, most wikis used a template Template:! with its contents only a raw pipe character (|
), since MW 1.24 a {{!}}
magic word replaced this kludge. This 'hides' the pipe from the MediaWiki parser, ensuring that it is not considered until after all the templates and variables on a page have been expanded. It will then be interpreted as a table row or column separator. Alternatively, raw HTML table syntax can be used, although this is less intuitive and more error-prone.
You can also escape the pipe character for display as a plain, uninterpreted character using an HTML entity: |
.
Описание | Вы вводите | Вы получаете |
---|---|---|
Escaping pipe character as table row/column separator | {{!}} |
| |
Escaping pipe character as a plain character | | |
| |
Зачистка пробелов
Пробелы, включая новые строки, табуляции и пробелы, удаляются из начала и конца всех параметров функций парсера. Если это нежелательно, то сравнение строк может быть сделано после того, как они будут заключены в кавычки.
{{#ifeq: foo | foo | equal | not equal }}
→ equal{{#ifeq: "foo " | " foo" | equal | not equal }}
→ not equal
Чтобы предотвратить обрезку деталей then и else, см. раздел m:Template:If. Некоторые люди достигают этого с помощью <nowiki > </nowiki> вместо пробелов
foo{{#if:|| bar }}foo
→ foobarfoofoo{{#if:||<nowiki /> bar <nowiki />}}foo
→ foo bar foo
Однако, этот метод можно использовать только для отображения "одного" символа пробела, так как синтаксический анализатор сжимает несколько символов пробела в строке в один.
<span style="white-space: pre;">foo{{#if:||<nowiki/> bar <nowiki/>}}foo</span>
→ foo bar foo
Например, white-space: pre
используется для принудительного сохранения белого пространства браузером, но даже при этом пробелы не отображаются. Это происходит потому, что пробелы очищаются программным обеспечением, прежде чем быть отправленными в браузер.
Можно обойти это поведение, заменив пробелы на
("breakable space") или
("non-breakable space"), поскольку они не изменяются программным обеспечением:
<span style="white-space: pre;">foo{{#if:||   bar   }}foo</span>
→ foo bar foofoo{{#if:|| bar }}foo
→ foo bar foo
Смотрите также
- Справка:Функции парсера в шаблонах
- m:Help:Calculation
- m:Help:Newlines and spaces
- m:Help:Comparison between ParserFunctions syntax and TeX syntax
- Справка:Волшебные слова
- Parser function hooks , an (incomplete) list of parser functions added by core and extensions.
- Module:String obsoleting Extension:StringFunctions
- Расширение:PhpTags
- Parser functions for Wikibase (the extensions that enables Wikidata): d:Special:MyLanguage/Wikidata:How to use data on Wikimedia projects
Примечания
- ↑ Prior to r86805 in 2011 this was not the case.
- ↑ ParserFunctions.php at phabricator.wikimedia.org