Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
MainPage
Community portal
Recent changes
Random page
Help
Special pages
Donate
Search
Search
English
Appearance
Log in
Request account
Personal tools
Log in
Request account
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Printable version
In other projects
Appearance
move to sidebar
hide
Settings
Group
Category:Maintenance
Help:Blocking users
Help:Bots
Help:Categories
Help:Contents
Help:Deletion and undeletion
Help:Diff
Help:Editing pages
Help:ExpandTemplates
Help:Extension:ParserFunctions
Help:External searches
Help:Formatting
Help:Images
Help:Links
Help:Magic words
Help:Managing files
Help:Moving a page
Help:Namespaces
Help:Navigation
Help:Parser functions in templates
Help:Patrolled edits
Help:Preferences
Help:Protected pages
Help:Random page
Help:Random root page
Help:Range blocks
Help:Recent changes
Help:Redirects
Help:Skins
Help:Special pages
Help:Starting a new page
Help:Substitution
Help:System message
Help:Tables
Help:Talk pages
Help:TemplateData
Help:Templates
Help:TemplateStyles
Help:Tracking changes
Help:Undelete
Help:User contributions
Help:Watchlist
Help:What links here
Manual:Expr parser function syntax
Manual:Extending wiki markup
Manual:Hooks
Manual:Magic words
Manual:Messages API
Manual:Parser functions
Module:Arguments/doc
Module:Int/doc
Module:Message box/configuration/doc
Module:Message box/doc
Module:Template translation/doc
Module:Transcluder/doc
Module:Version/doc
Module:Yesno/doc
Parser extension tags
Parser function extensions
Project:Language policy
Template:Admin tip
Template:Advanced user manual
Template:Anontools
Template:ApiEx
Template:Autocat
Template:Auxiliary template common notice
Template:Branching
Template:Bugfix
Template:Bugzilla
Template:Button
Template:Candidate
Template:Caution
Template:Clarify
Template:Collapse top
Template:Component
Template:Deprecated-inline
Template:Description missing
Template:Distinguish
Template:Documentation
Template:Documentation subpage
Template:Done
Template:EmptyCatGood
Template:Escape template list
Template:Excerpt
Template:Extension development
Template:Fixtext
Template:For
Template:Further
Template:Help
Template:High-risk
Template:Historical
Template:I18n navigation
Template:In progress
Template:Intricate template
Template:Introduced-inline
Template:IRC
Template:Localized link
Template:Localized link/messagedoc
Template:Magic words
Template:Main
Template:MainPage
Template:Markup
Template:Markup/row
Template:Mbox templates
Template:Module rating
Template:Move
Template:MW version
Template:MW version/layout
Template:N/a
Template:Navbar
Template:Newarticletext
Template:No
Template:Not done
Template:Note
Template:Optional
Template:Parser functions nav
Template:Partially done
Template:PD Help Page
Template:Phabricator
Template:Ptag
Template:Purge
Template:Recentchangestext
Template:Removed-inline
Template:Required
Template:Rev
Template:Security
Template:See
Template:See also
Template:Sp-contributions-footer
Template:Sp-contributions-footer-anon
Template:Special page
Template:Template shortcut
Template:Template test cases notice
Template:TemplateData header
Template:Thankyou
Template:To do
Template:Tracked
Template:Translatable
Template:Translatable template name
Template:Unusedtemplatestext
Template:Update
Template:Used in system
Template:Watchlists navigation
Template:Why
Template:WikiNonStop News
Template:Yes
TemplateData
Language
aa - Afar
aae - Arbëresh
ab - Abkhazian
abr - Abron
abs - Ambonese Malay
ace - Acehnese
acf - Saint Lucian Creole
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aig - Antiguan and Barbudan Creole English
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
apc - Levantine Arabic
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgc - Haryanvi
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Rinconada Bikol
bug - Buginese
bug-bugi - Buginese (Buginese script)
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
ccp - Chakma
cdo - Mindong
cdo-hant - Mindong (Traditional Han script)
cdo-latn - Mindong (Latin script)
ce - Chechen
ceb - Cebuano
ch - Chamorro
chn - Chinook Jargon
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cop - Coptic
cps - Capiznon
cpx - Puxian
cpx-hans - Puxian (Simplified Han script)
cpx-hant - Puxian (Traditional Han script)
cpx-latn - Puxian (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Dobrujan Tatar
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Southern Dagaare
din - Dinka
diq - Dimli
dlg - Dolgan
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dua - Duala
dv - Divehi
dz - Dzongkha
ee - Ewe
efi - Efik
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fvr - Fur
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan
gan-hans - Gan (Simplified Han script)
gan-hant - Gan (Traditional Han script)
gcf - Guadeloupean Creole
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
hak-hans - Hakka (Simplified Han script)
hak-hant - Hakka (Traditional Han script)
hak-latn - Hakka (Latin script)
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hke - Hunde
hno - Northern Hindko
ho - Hiri Motu
hoc-latn - Ho (Latin script)
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
iba - Iban
ibb - Ibibio
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
isv-cyrl - Interslavic (Cyrillic script)
isv-latn - Interslavic (Latin script)
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kaj - Jju
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
kge - Komering
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
knc - Central Kanuri
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kusaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
ljp - Lampung Api
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lua - Luba-Lulua
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mui - Musi
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nahuatl
nan - Minnan
nan-hant - Minnan (Traditional Han script)
nan-latn-pehoeji - Minnan (Pe̍h-ōe-jī)
nan-latn-tailo - Minnan (Tâi-lô)
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
nit - Southeastern Kolami
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nr - South Ndebele
nrm - Norman
nso - Northern Sotho
nup - Nupe
nv - Navajo
ny - Nyanja
nyn - Nyankole
nyo - Nyoro
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pap-aw - Papiamento (Aruba)
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Pitcairn-Norfolk
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qqq - Message documentation
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rut - Rutul
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sas - Sasak
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - Serbian (Cyrillic script)
sr-el - Serbian (Latin script)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Atayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tig - Tigre
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
ttj - Tooro
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wlx - Wali
wo - Wolof
wuu - Wu
wuu-hans - Wu (Simplified Han script)
wuu-hant - Wu (Traditional Han script)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yua - Yucatec Maya
yue - Cantonese
yue-hans - Cantonese (Simplified Han script)
yue-hant - Cantonese (Traditional Han script)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zgh-latn - Standard Moroccan Tamazight (Latin script)
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
<languages /> {{Magic words}} [[File:MediaWiki-extensions-icon.svg|125px|alt=MediaWiki extensions|{{dir|{{pagelang}}|left|right}}]] <span lang="en" dir="ltr" class="mw-content-ltr">Parser functions, added in MediaWiki 1.7, are a type of extension that integrate closely with the parser.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The phrase "parser function" should not be confused with {{ll|Extension:ParserFunctions}}, which is a collection of simple parser functions.</span> <span lang="en" dir="ltr" class="mw-content-ltr">(See {{ll|Help:Extension:ParserFunctions}} for those.)</span> <div lang="en" dir="ltr" class="mw-content-ltr"> == Description == </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Whereas a [[Special:MyLanguage/Manual:Tag extensions|tag extension]] is expected to take unprocessed text and return HTML to the browser, a parser function can 'interact' with other wiki elements in the page. For example, the output of a parser function could be used as a [[Special:MyLanguage/Help:Templates#Parameters|template parameter]] or in the construction of a [[Special:MyLanguage/Help:Link|link]]. </div> <div lang="en" dir="ltr" class="mw-content-ltr"> The typical syntax for a parser function is: </div> <blockquote><nowiki> {{ #functionname: param1 | param2 | param3 }} </nowiki></blockquote> <span lang="en" dir="ltr" class="mw-content-ltr">For more information, see {{tmpl|0={{method doclink | class=MediaWiki\Parser\Parser | anchor=a34da5613dad9dd0a5e921aa7bceba3cf|method=$1}}|the documentation}} for {{phpi|Parser::setFunctionHook ( $id, $callback, $flags {{=}} 0 )}}.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This documentation states:</span> :<span lang="en" dir="ltr" class="mw-content-ltr">The callback function should have the form:</span> ::<code>function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }</code> :<span lang="en" dir="ltr" class="mw-content-ltr">Or with <code>SFH_OBJECT_ARGS</code>:</span> ::<code>function myParserFunction( $parser, $frame, $args ) { ... }</code> <span lang="en" dir="ltr" class="mw-content-ltr">The first variant of the call passes all arguments as plain text.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The second passes all arguments as an array of {{ll|Manual:PPNode.php|PPNode}}s, except for the first (<code>$args[0]</code>), which is currently text, though this may change in the future.</span> <span lang="en" dir="ltr" class="mw-content-ltr">These represent the unexpanded wikitext.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The <code>{{ll|Manual:PPFrame.php|$frame}}</code> parameter can be used to expand these arguments as needed.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This is commonly used for conditional processing so that only the {{phpi|true}} case is evaluated with an <code>if</code>-or-<code>switch</code>-like parser function.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The frame object can also climb up the document tree to get information about the caller and has functions to determine and manage call depth, time-to-live, and whether the result of the parser function is volatile.</span> <div lang="en" dir="ltr" class="mw-content-ltr"> Creating a parser function is slightly more complicated than creating a new tag because the function name must be a [[Special:MyLanguage/Help:Magic words|magic word]], a keyword that supports aliases and localization. </div> <div lang="en" dir="ltr" class="mw-content-ltr"> == Simple example == </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Below is an example of an extension that creates a parser function. </div> <div lang="en" dir="ltr" class="mw-content-ltr"> The registration goes into '''extension.json''' and the code into '''src/ExampleExtensionHooks.php''' respectively: </div> {| class="wikitable" |- ! <span lang="en" dir="ltr" class="mw-content-ltr">Standard:</span> ! <span lang="en" dir="ltr" class="mw-content-ltr">Using the HookHandler interface:</span> |- !colspan="2"| extension.json |- | {{ExtensionJsonFile |type=parserhook |extension=ExampleExtension }} | {{Code |lang=json | { "name": "ExampleExtension", "author": "Me", "version": "1.0.0", "url": "https://www.mediawiki.org/wiki/Extension:ExampleExtension", "descriptionmsg": "{{lc:ExampleExtension}}-desc", "license-name": "GPL-2.0-or-later", "type": "parserhook", "MessagesDirs": { "ExampleExtension": [ "i18n" ] }, "AutoloadClasses": { "ExampleExtensionHooks": "src/ExampleExtensionHooks.php" }, "ExtensionMessagesFiles": { "ExampleExtensionMagic": "ExampleExtension.i18n.php" }, "Hooks": { "ParserFirstCallInit": "onParserFirstCallInit" }, "HookHandlers": { "ExampleExtensionHooks": { "class": "MediaWiki\\Extension\\ExampleExtension\\Hooks" } }, "manifest_version": 1 } }} |- !colspan="2"| ExampleExtensionHooks.php |- |<syntaxhighlight lang="php"> <?php class ExampleExtensionHooks { // Register any render callbacks with the parser public static function onParserFirstCallInit( Parser $parser ) { // Create a function hook associating the <code>example</code> magic word with renderExample() $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] ); } // Render the output of {{#example:}}. public static function renderExample( Parser $parser, $param1 = '', $param2 = '', $param3 = '' ) { // The input parameters are wikitext with templates expanded. // The output should be wikitext too. $output = "param1 is $param1 and param2 is $param2 and param3 is $param3"; return $output; } } </syntaxhighlight> | <syntaxhighlight lang="php"> <?php class ExampleExtensionHooks implements ParserFirstCallInitHook { // Register any render callbacks with the parser public function onParserFirstCallInit( $parser ) { // Create a function hook associating the example magic word with renderExample() $parser->setFunctionHook( 'example', [ $this, 'renderExample' ] ); } // Render the output of {{#example:}}. public function renderExample( $parser, $param1 = '', $param2 = '', $param3 = '' ) { // The input parameters are wikitext with templates expanded. // The output should be wikitext too. $output = "param1 is $param1 and param2 is $param2 and param3 is $param3"; return $output; } } </syntaxhighlight> |} <div lang="en" dir="ltr" class="mw-content-ltr"> Another file, '''ExampleExtension.i18n.php''', in your extension directory (Not in the src/ subdirectory) should contain: </div> <syntaxhighlight lang="php"> <?php /** * @license GPL-2.0-or-later * @author Your Name (YourUserName) */ $magicWords = []; /** English * @author Your Name (YourUserName) */ $magicWords['en'] = [ 'example' => [ 0, 'example' ], ]; </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> With this extension enabled, </div> * {{#example: hello | hi | hey}} <span lang="en" dir="ltr" class="mw-content-ltr">produces:</span> * param1 is hello and param2 is hi and param3 is hey {{note|1=<span lang="en" dir="ltr" class="mw-content-ltr">This magicWords array is not optional. If it is omitted, the parser function simply will not work; the {{#example: hello | hi}} will be rendered as though the extension were not installed.</span> <span lang="en" dir="ltr" class="mw-content-ltr">If only the language-specific array is initialized and not the magicWords array itself, this can cause localization errors as translations from other extensions leak into yours.</span> <span lang="en" dir="ltr" class="mw-content-ltr">You can associate magic words inline in PHP rather than through a i18n file.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This is useful when defining hooks in <code>LocalSettings.php</code></span> <syntaxhighlight lang="php"> MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['MAG_CUSTOM', 'custom']; </syntaxhighlight> }} <div lang="en" dir="ltr" class="mw-content-ltr"> === Within LocalSettings.php === </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Magic words and their handling parser functions can be defined entirely in LocalSettings.php. </div> <syntaxhighlight lang="php"> $wgHooks['ParserFirstCallInit'][] = function ( Parser $parser ) { MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['wikicodeToHtml', 'wikicodeToHtml']; $parser->setFunctionHook( 'wikicodeToHtml', 'wikicodeToHtml' ); }; function wikicodeToHtml( Parser $parser, $code = '' ) { $title = $parser->getTitle(); $options = $parser->Options(); $options->enableLimitReport(false); $parser = $parser->getFreshParser(); return [$parser->parse($code, $title, $options)->getText(), 'isHTML' => true]; } </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> === Longer functions === </div> <div lang="en" dir="ltr" class="mw-content-ltr"> For longer functions, you may want to split the hook functions out to a _body.php or .hooks.php file and make them static functions of a class. Then you can load the class with {{ll|Manual:$wgAutoloadClasses|$wgAutoloadClasses}} and call the static functions in the hooks; e.g.: </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Put this in your <code>extension.json</code> file: </div> <syntaxhighlight lang="json"> "Hooks": { "ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit" }, "AutoloadClasses": { "ExampleExtensionHooks": "src/ExampleExtensionHooks.php" } </syntaxhighlight> * <small><span lang="en" dir="ltr" class="mw-content-ltr">See: [[Special:MyLanguage/Manual:Hooks#Writing_an_event_handler|writing an event handler]] for other styles.</span></small> <div lang="en" dir="ltr" class="mw-content-ltr"> Then put this in your <code>src/ExampleExtensionHooks.php</code> file: </div> <syntaxhighlight lang="php"> class ExampleExtensionHooks { public static function onParserFirstCallInit( Parser $parser ) { $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] ); } } </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> == Parser interface == </div> <div lang="en" dir="ltr" class="mw-content-ltr"> === Controlling the parsing of output === </div> <div lang="en" dir="ltr" class="mw-content-ltr"> To have the wikitext returned by your parser function be fully parsed (including expansion of templates), set the <code>noparse</code> option to {{phpi|false}} when returning: </div> <syntaxhighlight lang="php"> return [ $output, 'noparse' => false ]; </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> It seems the default value for <code>noparse</code> changed from {{phpi|false}} to {{phpi|true}}, at least in some situations, sometime around version 1.12. </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Conversely, to have your parser function return HTML that remains unparsed, rather than returning wikitext, use this: </div> <syntaxhighlight lang="php"> return [ $output, 'noparse' => true, 'isHTML' => true ]; </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> === Naming === </div> <span lang="en" dir="ltr" class="mw-content-ltr">By default, MW adds a hash character (number sign, <code>#</code>) to the name of each parser function.</span> <span lang="en" dir="ltr" class="mw-content-ltr">To suppress that addition (and obtain a parser function with no <code>#</code> prefix), include the ''SFH_NO_HASH'' constant in the optional flags argument to setFunctionHook, as described [[#The setFunctionHook hook|below]].</span> <div lang="en" dir="ltr" class="mw-content-ltr"> When choosing a name without a hash prefix, note that transclusion of a page with a name starting with that function name followed by a colon is no longer possible. In particular, avoid function names equal to a namespace name. In the case that interwiki transclusion [https://lists.wikimedia.org/hyperkitty/list/mediawiki-l@lists.wikimedia.org/thread/3M53FBQ66B4EZNU6XMJQRFG3TVCW7WQO/] is enabled, also avoid function names equal to an interwiki prefix. </div> <div lang="en" dir="ltr" class="mw-content-ltr"> === The setFunctionHook hook === </div> <span lang="en" dir="ltr" class="mw-content-ltr">For more details of the interface into the parser, see the documentation for setFunctionHook in includes/Parser.php.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Here's a (possibly dated) copy of those comments:</span> '''function setFunctionHook( $id, $callback, $flags = 0 )''' <div lang="en" dir="ltr" class="mw-content-ltr"> '''Parameters:''' </div> * string $id – <span lang="en" dir="ltr" class="mw-content-ltr">The magic word ID</span> * mixed $callback – <span lang="en" dir="ltr" class="mw-content-ltr">The callback function (and object) to use</span> * integer $flags – <span lang="en" dir="ltr" class="mw-content-ltr">Optional. Values:</span> :* <code>SFH_NO_HASH</code> (1) – <span lang="en" dir="ltr" class="mw-content-ltr">constant if you call the function without <code>#</code>.</span> :* <code>SFH_OBJECT_ARGS</code> (2) – <span lang="en" dir="ltr" class="mw-content-ltr">if you pass a PPFrame object and array of arguments instead of a series of function arguments, for which [[#Description|see above]].</span> :*<span lang="en" dir="ltr" class="mw-content-ltr">Defaults to 0 (no flags).</span> <div lang="en" dir="ltr" class="mw-content-ltr"> '''Return value:''' The old callback function for this name, if any </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Create a function, e.g., <code><nowiki>{{#sum:1|2|3}}</nowiki></code>. The callback function should have the form: </div> <syntaxhighlight lang="php" style="overflow:auto;"> function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... } </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> The callback may either return the text result of the function, or an array with the text in element 0, and a number of flags in the other elements. The names of the flags are specified in the keys. Valid flags are: </div> {| class="wikitable" ! <span lang="en" dir="ltr" class="mw-content-ltr">Name</span> !! <span lang="en" dir="ltr" class="mw-content-ltr">Type</span> !! <span lang="en" dir="ltr" class="mw-content-ltr">Default</span> ! <span lang="en" dir="ltr" class="mw-content-ltr">Description</span> |- | found || <span lang="en" dir="ltr" class="mw-content-ltr">Boolean</span> || {{phpi|true}} | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if the text returned is valid and processing of the template must stop.</span> |- | text || ? || ? | <span lang="en" dir="ltr" class="mw-content-ltr">The text to return from the function.</span> <span lang="en" dir="ltr" class="mw-content-ltr">If isChildObj or isLocalObj are specified, this should be a DOM node instead.</span> |- | noparse || {{Tunit|id=125|content=Boolean}} || {{phpi|true}} | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if text should not be preprocessed to a DOM tree, e.g. unsafe HTML tags should not be stripped, etc.</span> |- | isHTML || {{Tunit|id=125|content=Boolean}} || ? | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if the returned text is HTML and must be armoured against wikitext transformation.</span> <span lang="en" dir="ltr" class="mw-content-ltr">[[Manual talk:Parser functions#isHTML - almost but not _entirely|But see discussion]]</span> |- | nowiki || {{Tunit|id=125|content=Boolean}} || <span lang="en" dir="ltr" class="mw-content-ltr">usually {{phpi|false}}</span> | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if wiki markup in the return value (text) should be escaped.</span> |- | isChildObj || {{Tunit|id=125|content=Boolean}} || ? | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if the text is a DOM node needing expansion in a child frame.</span> |- | isLocalObj || {{Tunit|id=125|content=Boolean}} || ? | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if the text is a DOM node needing expansion in the current frame.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The default value depends on other values and outcomes.</span> |- | preprocessFlags || ? || {{phpi|false}} | <span lang="en" dir="ltr" class="mw-content-ltr">Optional {{ll|Manual:PPFrame.php|PPFrame}} flags to use when parsing the returned text.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This only applies when noparse is {{phpi|false}}.</span> |- | title || ? || {{phpi|false}} | <span lang="en" dir="ltr" class="mw-content-ltr">The {{ll|Manual:Title.php|Title}} object where the text came from.</span> |- | forceRawInterwiki || {{Tunit|id=125|content=Boolean}} || ? | <span lang="en" dir="ltr" class="mw-content-ltr">{{phpi|true}} if interwiki transclusion must be forced to be done in raw mode and not rendered.</span> |} <div lang="en" dir="ltr" class="mw-content-ltr"> === Expensive parser functions === </div> {{see also|Manual:Template limits#Expensive parser function calls}} <span lang="en" dir="ltr" class="mw-content-ltr">Some parser functions represent a significant use of a wiki's resources and should be marked as "expensive".</span> <span lang="en" dir="ltr" class="mw-content-ltr">The number of expensive parser functions on any given page is limited by the {{ll|Manual:$wgExpensiveParserFunctionLimit|$wgExpensiveParserFunctionLimit}} setting.</span> <span lang="en" dir="ltr" class="mw-content-ltr">What counts as expensive is left up to the function itself, but typically, anything that is likely to cause a delay that extends beyond simple processing of data should be considered.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This includes things like database reads and writes, launching a shell script synchronously, or file manipulation.</span> <span lang="en" dir="ltr" class="mw-content-ltr">On the other hand, not all such functions should necessarily be tagged.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Semantic MediaWiki, for example, only marks a percentage of its database reads as expensive.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This is due to the fact that on certain data-intensive pages, it could easily overflow the normal expensive parser function limits.</span> <span lang="en" dir="ltr" class="mw-content-ltr">In cases like this, the potential for noticeably slower performance that doesn't get flagged as expensive is a trade-off to having the functionality that SMW offers.</span> <span lang="en" dir="ltr" class="mw-content-ltr">To mark your parser function as expensive, from within the body of the function's code, use <syntaxhighlight lang=php inline>$result = $parser->incrementExpensiveFunctionCount();</syntaxhighlight>.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The return value will be {{phpi|false}} if the expensive function limit has been reached or exceeded.</span> <div lang="en" dir="ltr" class="mw-content-ltr"> ==Named parameters== </div> <div lang="en" dir="ltr" class="mw-content-ltr"> Parser functions do not support named parameters the way templates and tag extensions do, but it is occasionally useful to fake it. Users are often accustomed to using vertical bars ( <code>|</code> ) to separate arguments, so it's nice to be able to do that in the parser function context, too. Here's a simple example of how to accomplish this: </div> <syntaxhighlight lang="php" style="overflow:auto;"> function ExampleExtensionRenderParserFunction( &$parser ) { // Suppose the user invoked the parser function like so: // {{#myparserfunction: foo=bar | apple=orange | banana }} $options = extractOptions( array_slice( func_get_args(), 1 ) ); // Now you've got an array that looks like this: // [foo] => 'bar' // [apple] => 'orange' // [banana] => true // Continue writing your code... } /** * Converts an array of values in form [0] => "name=value" into a real associative array in form [name] => value * If no = is provided, true is assumed like this: [name] => true * * @param array string $options * @return array $results */ function extractOptions( array $options ) { $results = []; foreach ( $options as $option ) { $pair = array_map( 'trim', explode( '=', $option, 2 ) ); if ( count( $pair ) === 2 ) { $results[ $pair[0] ] = $pair[1]; } if ( count( $pair ) === 1 ) { $results[ $pair[0] ] = true; } } return $results; } </syntaxhighlight> <div lang="en" dir="ltr" class="mw-content-ltr"> ==See also== </div> <div lang="en" dir="ltr" class="mw-content-ltr"> General and related guides: </div> * <span lang="en" dir="ltr" class="mw-content-ltr">{{ll|Manual:Developing extensions}}, or for more general information about extensions, see {{ll|Manual:Extensions}} and {{ll|Extensions FAQ}}.</span> * {{ll|Manual:Tag extensions}} * {{ll|Manual:Magic words}} <span lang="en" dir="ltr" class="mw-content-ltr">Code:</span> * {{ll|Manual:Parser.php}} * {{ll|Manual:Hooks/ParserFirstCallInit}} * {{ll|Parser function hooks}} – <span lang="en" dir="ltr" class="mw-content-ltr">an (incomplete) list of parser functions provided by core and extensions</span> <div lang="en" dir="ltr" class="mw-content-ltr"> * The [https://github.com/JeroenDeDauw/ParserHooks#parserhooks Parser Hooks] PHP library, which provides an object orientated interface for declarative parser hooks </div> * {{ll|Manual:Extension data}} <span lang="en" dir="ltr" class="mw-content-ltr">Examples:</span> * <span lang="en" dir="ltr" class="mw-content-ltr">The [[Special:MyLanguage/Extension:ParserFunctions|ParserFunctions extension]] is a well-known collection of parser functions.</span> * {{ll|Help:Extension:ParserFunctions}} * {{ll|Category:Parser function extensions}} {{Extension development}} [[Category:MediaWiki development{{#translation:}}]] [[Category:Parser extensions{{#translation:}}|*]] [[Category:Wiki markup{{#translation:}}|Parser functions]] [[Category:Customization techniques{{#translation:}}|Parser functions]] [[Category:Sample code{{#translation:}}]]
Search
Search
Export translations
Add topic