Bantuan:Templat
Tolong bantu menterjemahkan sebahagian laman ini. Laman ini memerlukan kemaskini dalam Bahasa Melayu piawai Dewan Bahasa dan Pustaka. Sila membantu, bahan-bahan boleh didapati di Templat (Inggeris). Jika anda ingin menilai laman ini, anda mungkin mahu menyemak di terjemahan Google. Walau bagaimanapun, jangan menambah terjemahan automatik kepada laman, kerana ini biasanya mempunyai kualiti yang sangat teruk. Sumber-sumber bantuan: Pusat Rujukan Persuratan Melayu. |
Templat merupakan satu halaman yang diciptakan khusus untuk transklusi – proses MediaWiki untuk memasukkan isi kandungan suatu laman di dalam halaman yang lain. Apa-apa saja laman boleh ditransklusikan, tetapi templat telah direka khusus untuk tujuan tersebut, biasanya bagi bahan-bahan berulang yang juga mungkin perlu ditampilkan pada beberapa rencana atau laman Wikimedia. Templat lazimnya digunakan bagi pesanan plat dandang, amaran atau notis piawai, kotak maklumat, kotak pandu arah dan yang serupa dengannya.
Bagi pengenalan ringkas mengenai perkara berkenaan, sila lihat panduan ringkas bagi templat.
Bagi senarai templat yang biasa digunakan, sila lihat Pesanan templat.
Umum
[sunting | sunting sumber]Pengenalan
[sunting | sunting sumber]Templat-templat mungkin mengandungi apa wikiteks yang mungkin kita inginkan, termasuklah panggilan-panggilan ke templat-templat lain. Mereka mempunyai kapasiti pengaturcaraan terhad: nilai-nilai yang mengikut batasan tertentu (dipanggil parameter), pengiraan dan pemecahan (menggunakan fungsi Parser), dan laluan kepada pemboleh -pemboleh ubah wiki-spesifik (perkataan-perkataan ajaib), seperti tarikh, masa dan nama-nama halaman.
Untuk menggunakan satu templat dalam satu artikel atau halaman, satu tag templat (dalam bentuk {{template name}}; name templat yang ditutup di dalam kedua-dua kurungan) ditambah di mana anda hendak ia ditimbulkan. Apabila seseorang itu hendak membaca halaman itu, pelayan-pelayan Wikimedia akan ambil isi kandungan pada templat, buatkan apa-apa pengiraan yang tidak perlu dibuat, dan gantikan tag templat dalam wikitext dengan isi kandungan templat itu yang diproses.
Muka surat templat dan ruang nama
[sunting | sunting sumber]Templat-templat mempunyai ruang nama mereka sendiri yang menggunakan prefiks "Templat:" (serupa dengan ruang nama "Pengguna:", "Bantuan:", dan "Talk:" yang dikenali). (Bahasa-bahasa Wikipedia lain mungkin menggunakan prefiks berbeza, seperti "Vorlage:", "Modèle:", "Sjabloon:", walaupun "Template:" boleh digunakan pada tempat-tempat ini.)
Kebanyakan templat wujud di dalam ruang nama, dan boleh ditemui dalam halaman bertajuk "Template:Template name". Walau bagaimanapun, pengguna kadangkala membuat templat dalam ruang nama lain seperti User: namespace. Transklusi boleh diguna pakai dari mana-mana ruang nama,[1] tetapi kelebihan ruang nama templat ialah awalan "Templat:" tidak diperlukan apabila mentransklusi.
Nama-nama templat adalah sama dengan nama halaman yang lain: kes-sensitif melainkan huruf pertama dan ruang tidak diperlainkan dengan tanda garis bawah. Andai simbol # (biasanya digunakan bagi memaut bahagian suatu halaman) muncul dalam transklusi, simbol tersebut dan mana-mana karakter susulan tidak diendahkan.
Halaman templat, seperti kebanyakan halaman lain, ada halaman perbincangan yang berkaitan di mana penyunting boleh membincang apa-apa isu berkaitan templat itu. (atas sebab ini, templat tidak sepatutnya diletakkan di ruang nama "Talk:", meskipun dengan tujuan menggunakannya pada halaman perbincangan; lantaran halaman perbincangan tidak mempunyai halaman perbincangannya sendiri, tiada halaman untuk membincangkan templat.)
Templat hanya berkesan dalam projek Wikimedia tertentu. Salinan templat tersebut mesti dibuat dalam setiap projek andai templat itu hendak digunakan dalam projek lain.
Templat penggunaan
[sunting | sunting sumber]To transclude a template into another page, use the following syntax (called a template tag):
- {{ template name | parameter | parameter | ... }}
This consists of the template name and various parameters that are passed to the template, where each parameter is separated by a vertical bar (or pipe), and the entirety is surrounded by doubled curly braces, {{...}}. The template tag should be placed in a page or article wherever the template is intended to appear. The "Template:" prefix is never needed for transclusion, only for finding and editing the template itself (though if the template is created in a different namespace that prefix is needed). Not all templates have parameters, and not all templates that have parameters need to have values provided, so sometimes {{ template name }} is sufficient to use a template. If a parameter is needed, but a value not provided by the user, the template may render with something like {{{...}}} in the text, where the '...' might be a number or a parameter name. This is to inform the user that a named or unnamed parameter is missing, and can be avoided by using default values for the parameter.
Parameters come in two basic forms:
- unnamed parameters: values that are put into the template in the order they appear
- {{ template name|parameter1|parameter2|...}}
- named parameters: values associated with a particular named key in the template
- {{ template name | parametername1 = parameter1 | parametername2 = parameter2 | ... }}
These may be mixed:
- {{ template name |parameter1|parameter2| parametername1 = parameter3 | parametername2 = parameter4 | ... }}
By convention named parameters are listed last, though that is not a requirement. Whitespace characters (spaces, tabs, returns) are stripped from the beginnings and ends of named parameter values (unnamed parameters are unaffected), but not from the middle: thus {{ ... | myparam = this is a test }} will be treated as though the user had typed {{ ... |myparam=this is a test}}.
Template pages themselves may include material that is not transcluded with the template (such as documentation or Wikimedia categories that the template itself belongs to), or material that is only used when the page is transcluded (such as categories that apply to the transclusion page, but not the template). See the discussion of the includeonly and noinclude tags, below.
Attempting to transclude a template that does not exist produces a redlink, just like linking to any other nonexistent page. Following the link allows one to create that particular template.
Contoh penggunaan templat
[sunting | sunting sumber]Jika anda ingin mencuba templat-templat di bawah, sila gunakan templat kotak pasir
Templat dengan tiada parameter
[sunting | sunting sumber]Untuk melihat contoh templat yang paling mudah, perhatikan Template:Tc. Templat ini membantu mengalihkan huruf di "dalam" ke halaman lain. Contohnya, menyunting frasa berikut ke mana-mana halaman akan menghasilkan hasil seperti di bawah:
Penerangan | Perkataan yang dimasukkan | Hasilnya |
---|---|---|
Hanya {{Tc}} | {{tc}} | {{tlc|...}}
|
Hanya satu penggunaan {{tc}} dalam teks | {{tc}} 2009, with Barack Obama settling into the White House, we find the beginning of... | {{tlc|...}} 2009, with Barack Obama settling into the White House, we find the beginning of...
|
Penggunaan {{tc}} yang banyak dalam teks | {{tc}} 2009, with Barack Obama settl{{tc}}g {{tc}}to the White House, we f{{tc}}d the beg{{tc}}n{{tc}}g of... | {{tlc|...}} 2009, with Barack Obama settl{{tlc|...}} g {{tlc|...}} to the White House, we f{{tlc|...}} d the beg{{tlc|...}} n{{tlc|...}} g of...
|
Anda akan perasan bahawa templat tersebut hanya mengandungi huruf "dalam" apabila dikosongkan, walaupun ada teks penjelasan pada halaman templat ("Templat ini digunakan ..." klik pada pautan templat di atas untuk melihat). Jika anda menyunting halaman templat, (klik pautan ini), anda akan melihat semuanya kecuali huruf-huruf di "dalam" yang disertakan dalam 'noinclude', yang akan dibincangkan kemudian.
Templat parameter tiada nama
[sunting | sunting sumber]Transclusion with parameters is only slightly more complicated. For a quick example, the famous dead man's hand can be reproduced by the following templates, using unnamed parameters:
Description | Text Entered | Result after Processing |
---|---|---|
using three templates (Template:Clubs, Template:Diamonds, and Template:Spades) | {{ clubs |A}} {{ clubs |8}} {{ spades |A}} {{ spades |8}} {{ diamonds |9}} | A♣ 8♣ A♠ 8♠ 9♦ |
Using (Template:BridgeHandInline); not quite as pretty, but just one template, with four parameters. | {{ BridgeHandInline |A8||9|A8}} | ♠ A8 ♥ ♦ 9 ♣ A8 |
Using (Template:BridgeHandInline), but with a missing pipe separator | {{ BridgeHandInline |A8|9|A8}} | ♠ A8 ♥ 9 ♦ A8 ♣ {{{4}}} |
In the second example, the position of the parameter in the template tag determines which suit it belongs to. Thus, the first A8 (first slot) goes to spades, the empty position (second slot) goes to hearts, the 9 (third slot) goes to diamonds, the second A8 (fourth slot) goes to clubs. Note that the empty parameter position is counted; if the extra pipe is forgotten, as in the third example, the result is that the cards end up in the wrong positions, and a {{{4}}} appears, meaning that the template was expecting a value for the fourth positional parameter but none was provided. See the section on parameters and default values, below.
Templat dengan parameter bernama
[sunting | sunting sumber]Using named parameters is similar to using unnamed parameters. For example, Template:Payoff matrix (which is used in some game theory pages) gives a simple 2-by-2 grid with adjustable values, using the names UL, UR, DL, and DR to refer to Up Left, Up Right, Down Left and Down Right, and a Name parameter to add a name to the bottom of the matrix.
Description | Code | Result |
---|---|---|
Payoff matrix | {{payoff matrix | UL = 5 | UR = 7 | DL = 2 | DR = 9 | Name = Example usage }} | Templat:Payoff matrix |
Payoff matrix showing a default value for a missing parameter, and different ordering for the others | {{payoff matrix | DR = 9 | Name = Example usage | DL = 2 | UR = 7 }} | Templat:Payoff matrix |
In the second case, the order of the parameters has been altered without changing the result - one of the advantages that named parameters have over unnamed parameters - and one of the values (UL) has been removed entirely, allowing the template to insert the default value of "0, 0".
Parameter names are case sensitive, even in the first character. for example, using "dr = 9","Dr = 9" or "dR = 9" instead of "DR = 9" will cause the Down Right cell to display the default "0, 0". The alternate case versions are treated as different parameters and ignored by the template.
Penggantian
[sunting | sunting sumber]Generally, templates are processed into readable text when a user browses a page. This is the normal intention of a template: since the template is reevaluated each time it's used, changes to the template can propagate across many pages quickly and effortlessly. Occasionally, however, this is not appropriate. For instance, a user may want a template which returns a date or time that remains fixed, rather than changing each time the page is browsed. For those cases there is substitution, which is done by adding subst: before the template name in the template tag. substitution does exactly what its name suggests: rather than processing the template each time the page is browsed, substitution processes the template at the time the edit is saved, and replaces the template tag with the processed results.
For example, the template {{tc}} (as shown above) adds the letters "in" wherever it is placed. Thus, the wikitext bra{{tc}} will produce the word bra{{tlc|...}}
. The wikitext will always remain as bra{{tc}}, however, so if {{tc}} is changed so that it adds the letters "wn", the wikitext will produce brawn instead of brain. Substituting like so - bra{{subst:tc}} - will permanently change the wikitext to read brain, and later changes to the template {{tc}} will have no effect on the substituted text.
In general, substitution processes one level, so if the template in question contains other template tags, those template tags will be substituted in, rather than the processed results of those tags. This is a sometimes useful trick when debugging complex templates. For information on multi-level substitution, see Help:Substitution#Multilevel substitution. Articles where templates were substituted rather than transcluded are listed on WikiProject Check Wikipedia#Template programming element.
Lain-lain maklumat penggunaan
[sunting | sunting sumber]- To quote a template, creating a link to the template rather than actually invoking the template, use the "{{tl}}" template (the template link template). For example, using the text "{{tl|tc}}" creates a link to Template:Tc without actually doing what the template normally does, like so: {{tc}}.
- a list of all pages that a particular template is transcluded onto can be found by clicking the 'What links here' link on the main template page.
- a list of all the templates that a particular page transcludes can be found by clicking the Edit link on the page normally and scrolling down past the edit window. The list will include the entire template "tree", that is, any sub-templates called by other templates to produce the preview will also be listed. To find the actual templates used in the article page itself, you will need to search in the edit window text for template invocations (names included within the "{{...}}" wiki-template invocations).
- A list of templates used in a particular section can be found by clicking the Edit link for that section and then clicking Preview
- Likewise, a list of templates used in an old version of a page can be found by choosing the version from the page history, clicking the Edit link, and clicking Preview. Note that this only works to one level: the sub-templates listed will reflect the current state of the templates transcluded on the old page. There is no way to examine which sub-templates were transcluded at the time the old page was current.
- Templates may seem small compared to other pages on Wikimedia, but editing them can consume a tremendously disproportionate amount of system resources, particularly when they are transcluded on to large numbers of pages. When a change is made to a template, the MediaWiki software automatically places every page in which the template is transcluded onto the job queue to update the template links and ensure that any new page views will reflect the change. For very popular templates, it is better to create a copy in userspace or in a sandbox, make and test any needed changes there, present it on the template talk page to make sure there are no objections, and then introduce it as a single edit. See Wikipedia:Template test cases for a systematic way of doing so.
- In rare circumstances, templates may be so complex and invoke so many sub-templates that they impose a significant load on the parser software. This load can be checked by examining the generated HTML for a page and looking for the "NewPP limit report" comments, which show how relatively "expensive" the article page is.
Mencipta dan menyunting templat
[sunting | sunting sumber]Templates are created and edited in much the same way as any other page on WikiMedia: choose an appropriate name, navigate to that page, then click the Edit tab or create a new page as needed. The only real difference is that templates will normally be placed in the "Template:" namespace rather than the (unprefixed) article namespace. Anything that can be included on a normal page or article can be included on a template, including other templates (though as a practical matter templates will often have relatively small contents). Beyond that, templates have access to programming features - parameters, parser functions, and magic words - which allow for context dependent use,[2] and special tags that help control which information is transcluded and which is not.
When creating templates, it's best to follow a few simple principles:
- Choose a short, descriptive name. Some people suggest that template names be completely small caps, some that spaces in template names should be avoided, but there is currently no hard guideline.
- Make a quick search of template space to make sure that the template you're creating hasn't already been done. It is sometimes easier and better to enhance an already existent template than to create a new template from scratch.
- Make sure your template is properly documented and included in the correct categories. Categorizing your template and documenting it will make it easier for other editors to find and use.
- To add documentation, put the {{Documentation}} template inside 'noinclude' tags on the template page. This will create a documentation subpage that you can edit
- Categories that apply to the template itself should be added to the template page (inside 'noinclude' tags, with the {{Documentation}} template). Categories that are to be transcluded to the transclusion page should be placed on the template page inside 'includeonly' tags.
- Try to make your template modular: i.e. capable of standing on its own and in a variety of different page contexts, without breaking, producing poor output, or messing up a page's layout. In general, you want your template to be transparently useful to other editors - the more effort they have to put into understanding how your template is used, the less they will be willing to use it.
Fungsi Parser
[sunting | sunting sumber]Parser functions are the WikiMedia toolkit for simple branchings, calculations, text manipulations, and the like. As a group, they take one or more parameters and return a wikitext value based on the parameters. There are two basic forms for Parser functions (distinguished by whether a pound sign follows the opening brackets):
- Core parser functions, of the form {{functionName: parameter | parameter | ... }}. These functions are part of the core wikimedia software, and should be available in all projects.
- Parser functions from the parserFunctions extension, of the form {{#functionName: parameter | parameter | ... }}. These functions are part of the parserFunctions extension, and may not be available everywhere.
Parser functions are primarily used for the evaluation of parameters or magic words, in order to produce different results in different contexts.
Core parser functions generally deal with text manipulation and WikiMedia specific tasks.
Description | Text Entered | Result |
---|---|---|
Uppercasing text | {{uc: Heavens to BETSY! }} | HEAVENS TO BETSY! |
Lowercasing text | {{lc: Heavens to BETSY! }} | heavens to betsy! |
Getting a namespace name | {{NS: 1 }} | Perbincangan |
Getting a wikipedia URL | {{fullurl: pagename }} | //ms.wikipedia.org/wiki/Pagename |
The parserFunctions extension gives more more programming-oriented parser functions.
Description | Text Entered | Result |
---|---|---|
Testing between options | {{#ifeq: yes | yes | Hooray...! | Darn...! }} {{#ifeq: yes | no | Hooray...! | Darn...! }} |
Hooray...! Darn...! |
Testing if a parameter is set | {{#if: {{{param|}}} | Hooray...! | Darn...! }} | Darn...! |
making a calculation | {{#expr: ( 27 * 46 / pi ) round 2 }} | 395.34 |
These functions are discussed in greater detail on their respective help pages.
Parameter-Parameter
[sunting | sunting sumber]Parameters are special codes that allow wikitext to be fed to a template; the template can be constructed to produce different outcomes depending on the values of the parameters it receives. Parameters may have names, or may be referenced by the position of values provided in the template tag (the order of the parameters in the template itself is irrelevant). Parameters in a template take the form {{{...}}}, where the tripled curled-braces surround the name of a named parameter or the number of a positional parameter. Values entered for parameters can be quite long (see Help:Long parameter demo), and if needed the transclusion of an entire page may be used as the value for a parameter.
To see how parameters work, consider this example. Assume there is a template called 'peoplepets' that produces some text about people and their pets. A template tag for this template might look like the following:
- {{ peoplepets | John | Mary | age = 6 | Fido | small | kind = dog }}
- {{ peoplepets | Bill | Susan | age = 7 | Queenie | fat | kind = cat }}
The contents of the template itself, on the page Template:Peoplepets, looks as follows:
- {{{1}}} and {{{2}}} own a {{{4}}} [[{{{kind}}}]] named {{{3}}} who is {{{age}}} years old.
Thus, the two template tags above will transclude the following text, respectively:
- John dan Mary mempunyai seekor small dog bernama Fido yang berumur 6 tahun.
- Bill dan Susan mempunyai seekor fat cat bernama Queenie yang berumur 7 tahun.
Things to note:
- The numbering of positional parameters skips over named parameters (as with 'age' above)
- The leading and trailing spaces around the values of named parameters in the template tags are stripped by the template.
- This is not true for unnamed parameters, which preserve trailing and leading whitespace. However, browsers render multiple whitespace characters as a single space, so the extra spaces around 'Fido', 'fat' and the other unnamed parameter values aren't immediately visible. This can be confusing if unnamed parameters are used for something other than display, such as links.
- The order in which parameter values are used in the template doesn't matter.
- The number of a positional parameter is treated as though it were a name: {{ peoplepets | John | ... }} could have been written {{ peoplepets | 1 = John | ... }}. This is useful when positional parameters need to be entered out of order.
- Values may be empty. Here the second positional parameter and the 'age' parameter have empty values:
- Template tag:{{ peoplepets | John || age = | Fido | small | kind = dog }}
- Produces (note the missing words): John dan mempunyai seekor small dog bernama Fido yang berumur tahun.
- Values can remain unprovided. Here the 'kind' parameter has been omitted:
- Template tag: {{ peoplepets | John | Mary | age = 6 | Fido | small }}
- Produces (this displays the missing variable): John dan Mary mempunyai seekor small [[{{{kind}}}]] bernama Fido yang berumur 6 tahun.
Parameter default
[sunting | sunting sumber]Default values can be specified for parameters using the vertical pipe character: |. The above example template could be rewritten as follows (in which 'friend' is the default value for positional parameter 2, the 4th positional parameter defaults to emptiness, and the 'kind' of the pet defaults to 'dog'):
- {{{1}}} and {{{2|friend}}} own a {{{4|}}} [[{{{kind|dog}}}]] named {{{3}}} who is {{{age}}} years old.
A template tag like the following: {{ peoplepets | Bill || age = 7 | Queenie }} will then produce the phrase Bill and friend own a dog named Queenie who is 7 years old.
Latihan parameter dan susun atur tag
[sunting | sunting sumber]Parameters that are not used in the template are ignored if they are provided by the template tag. This was intended to prevent transclusions from breaking if a template is changed in a way that removes a parameter; there's no need to go to every page a template is transcluded onto and change the tags. This has an added benefit, however, of making some template tags more readable, through spacing, or by adding comments. Using {{t3d}}:
Description | Text Entered | Result |
---|---|---|
Adding comments using template {{t3d}} | {{t3d |a|b|c| row 1 |d|e|f| row 2 |g|h|i| row 3 }} |
a b c d e f |
Since {{t3d}} does not use parameters {{{4}}}, {{{8}}}, or {{{12}}} the 'row #' values have no effect on the produced wikitext.
Dummy named parameters can be used in any template tag; simply choose an unused parameter name and add it into the tag as 'unusedname = value'. One special case of a named dummy parameter is to use an empty string as the parameter name. This acts like a named parameter in that it isn't counted when assessing the unnamed parameter positions, but it doesn't risk accidentally conflicting with an actual named parameter.
Description | Text Entered | Result | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dummy variables with {{chess position}} | {{chess position|= comments go here 8 |rd|nd|bd|qd|kd|bd|nd|rd|= 7 |pd|pd|pd| | |pd|pd|pd|= 6 | | | | | | | | |= 5 | | | |pd|pd| | | |= standard opening 4 | |pl| | | | |pl| |= 3 | | | | | | | |bl|= odd move 2 |pl| |pl|pl|pl|pl| |pl|= 1 |rl|nl|bl|ql|kl| |nl|rl|= a b c d e f g h |30}} |
|
{{chess position}} uses the first 64 unnamed parameters to specify pieces; adding in unnumbered dummy parameters for comments would have required that the template be rewritten (or that the unnumbered parameters be specified explicitly using the '#=value' format).
Kekangan terhadap parameters dan nilai parameter
[sunting | sunting sumber]- Unnamed parameters cannot be assigned a value containing an equals sign (=); the parser will treat the equals sign as the assignment of a named parameter. There are several indirect means around this limitation:
- In the template, write the value as the default of an undefined parameter:
- {{{...| a=b }}}, where the ellipsis can be number of an unused positional parameter, or can be a blank string (a null parameter).
- In the article, assign the values to the template parameters with one of the following methods:
- {{templatename| 1= a=b }}, where the '1=' notation explicitly names the first unnamed parameter.
- Use the special template {{=}}, e.g. {{template name| a{{=}}b }}
- Use the HTML entity for an equals sign: =. This is only useful for text representation; If the equals sign needs to be processed as an actual equals sign (as in another template) this approach won't work.
- In the template, write the value as the default of an undefined parameter:
- Parameter values cannot contain vertical pipe (|) characters; the parser will treat the pipe character as a separator rather than as text. Pipes are possible within wikilinks (country=[[United States|USA]]) or nested templates (e.g. volume= {{convert|30|acre.ft|m3}}). Indirect means around this limitation are as follows:
- Use the special template {{!}}, which returns a valid pipe character. Use this method if you need something that will be read as an actual pipe character (for instance, if you're using the parameter to modify the structure of a wikitext table)
- Use the HTML entity for a vertical pipe: |. This is only useful for text representation; If the pipe needs to be processed as an actual pipe this approach won't work.
- Parameter values cannot contain unmatched sequential curled brackets - }} or {{. The parser will try to parse them as the beginning or ending of a template tag or parameter, and will throw errors somewhere. Parameters can, however, contain other parameters, magic words, or template tags.
- again, this can be circumvented using 'nowiki' tags or HTML entities.
Parameters do not get expanded when they are inside nowiki tags or XML-style extension tags. Thus, the following will not work within a template - <myextension xparam={{{tparam}}}> ... </myextension> - because the parameter is not expanded:
Because template tags, parser functions, magic words, and parameters are all defined using curled braces, there are times when their combined use can be ambiguous. For example, the construction {{{{{NAMESPACE}}}}} might be interpreted as:
- {{ {{{NAMESPACE}}} }} (a template tag whose name is specified by the named parameter NAMESPACE)
- {{{ {{NAMESPACE}} }}} (a parameter whose name is specified by the value of the magic word NAMESPACE).
In general, wherever the parser finds more than 3 opening braces in a row, it will assume it is a parameter if the matching closing braces are 3-in-a-row, or as a template tag if only two of the matching closing braces are contiguous. In some cases it is advisable to add a space in the opening brackets to clarify the construction. For instance, the {{{{{NAMESPACE}}}}} construction from above will always default to the first interpretation; it might be better to use {{{ {{NAMESPACE}}}}} or {{ {{{NAMESPACE}}}}} as required so that the intention of the code is clear to other editors.
Nesting templates
[sunting | sunting sumber]Templates may contain other templates - usually called 'nesting'. As the template is processed, the wikitext produced by any nested templates is transcluded into the nesting template, so that the final product is essentially processed from the most deeply nested template out. While fairly straight-forward in application, it involves some noteworthy quirks and tricks.
To pass a parameter value to a nested template, place a parameter tag as the value of one of the nested template's parameters.
- Examples:
- Template:A contains "the quick brown {{B|{{{3}}}}} jumped over...". This takes the value passed to the third positional parameter of Template:A and passes it as the first positional parameter of Template:B, then returns the wikitext produced by B as part of the phrase.
- Template:A contains "the quick brown {{B|waldo={{{3}}}}} jumped over...". As above, except the third positional parameter of Template:A is passed to the named parameter 'waldo' of Template:B.
Template parameters themselves can be chosen conditionally.
- Example:
- Template:A contains "the quick brown {{B|{{{3}}}=fox}} jumped over...". Template:A passes the word 'fox' to a parameter of Template:B that's named in A's third positional parameter.
The Wikimedia software will allow a template to call itself, but will stop after one iteration to prevent an infinite loop.
When a nested template contains unmatched curled-brackets - as in {{lb}} - the unmatched brackets are treated as text during processing, and do not affect the parsing of brackets in the nesting template. If the nested template is substituted, however, the substitution is processed first, and this will change how braces are parsed in the nesting template. This has little practical use, but can occasionally introduce unexpected errors.
See the help:advanced templates and meta:Help:Recursive conversion of wikitext for more information.
Noinclude, includeonly, and onlyinclude
[sunting | sunting sumber]Several tags are available to control what does and doesn't get transcluded from a template.[3] The three tags are noinclude, includeonly, and onlyinclude. They are used in the same fashion as standard HTML or XML blocks: opening and closing tags in angled brackets (e.g. <noinclude>affected wikitext</noinclude>).
Perhaps the most common issue with the use of these blocks is unwanted spaces or lines. It is important to remember that the effect of these tags ends immediately after the last angle bracket, not on the next line or with the next visible character.
These tags can be nested inside each other, though (for a given page) this really only applies to the 'onlyinclude' tag; nesting 'includeonly' and 'noinclude' tags is fairly pointless. Be careful not to split the tags, however. Constructions like this <onlyinclude>abc<includeonly>def</onlyinclude>ghi</includeonly> will not work as expected. Use the 'first opened, last closed' rule that is standard for XML.
Note further that expansions may not occur the way expected. For instance, ~<includeonly>~</includeonly>~~ will be displayed as ~~~ in the template, and will be transcluded as ~~~~, but it will not be expanded in either case (as user name or the name/date combination). The template would have to be substituted to get this wikitext to expand.
noinclude
[sunting | sunting sumber]The 'noinclude' tag is used to prevent text on the template page from being transcluded onto other pages. This is often used for:
- documentation
- categories that apply to the template itself
- interwiki links to related templates on other wikis.
Its use is straightforward:
- If this text were in a template page, this part would be transcluded
- <noinclude>but this text would not be transcluded</noinclude>
One of the peculiarities of 'noinclude' tags is that the text contained in them is actually processed, even though it is not included in the rendered output. This has to do with error reporting: the processor needs to retain the text while it checks that there is a valid </noinclude> closing tag, and this consumes system resources. For templates that are not heavily used, this is rarely a problem, but on some templates excess text (and interwiki links in particular) can create a tremendous overhead for the system. As a rule, interwikis and documentation should be placed on a /doc subpage (such as is generated automatically by the {{Documentation}} template).
includeonly
[sunting | sunting sumber]The 'includeonly' tag is the opposite of the 'noinclude' tag. Text within an include only block is only included when the page is transcluded, is does not appear on the template page itself. This is frequently used for:
- categories that apply to the transclusion page
- hiding messy text or error messages that occur on the template page itself (often because parameters that need a value are undefined)
Its use is straightforward:
- If this text were in a template page, this part would appear on the template page and on the transclusion page
- <includeonly>but this text would only appear on the transclusion page</includeonly>
onlyinclude
[sunting | sunting sumber]The 'onlyinclude' tag literally only includes the material that is between the tags; anything else on the page - even text within 'includeonly' tags, will appear on the template page but will not be included. This is not frequently used, but might be useful when only a small bit of text in the middle of an otherwise large page is to be transcluded. It is used like this:
- If this text were in a template page, this part would be visible there, but would not be transcluded
- <includeonly>This text would not be visible on the template page, nor would it be transcluded</includeonly>
- <onlyinclude>this text is all that would be transcluded</onlyinclude>
Magic words
[sunting | sunting sumber]There are three general types of magic words on Wikimedia pages. One - parser functions - are already discussed above. The second type - behavioral switches - involves page structure modifications which are of little use on templates. The last type, however - variables (or system variables) - are often used on templates. These magic words provide information directly from the system itself: local dates and times, information about the current articles or pages, and even information about the wiki itself.
System variables take the format {{...}} where the enclosed text is always entirely capitalized. A small number of system variables take a parameter as well, using the standard colon separator - {{MAGICWORD:parameter}}. If the enclosed text starts and ends with doubled underscores (__...__) it is a behavioral switch, not a variable.
Description | Text Entered | Result (for this help page) |
---|---|---|
Page names | {{PAGENAME}} {{FULLPAGENAME}} |
Templat Bantuan:Templat |
Name of the current namespace | {{NAMESPACE}} | Bantuan |
Number of registered users | {{NUMBEROFUSERS}} | 341,478 |
Number of pages in a given category | {{PAGESINCATEGORY:"Weird Al" Yankovic albums}} | 0 |
Current software version | {{CURRENTVERSION}} | 1.43.0-wmf.20 (ef87455) |
Timestamp of last revision | {{REVISIONTIMESTAMP}} | 20190301111046 |
The PAGENAME and NAMESPACE variables are particularly useful, and frequently used, to change template behavior based on context. For example, if the template transcludes a category link (e.g. cleanup templates, which transclude a link categorizing the page as a page which needs cleanup), it will often check the NAMESPACE variable to make sure that talk pages, user pages, or anywhere else the tag might incidentally be placed do not themselves get categorized as pages needing cleanup.
Other editing information
[sunting | sunting sumber]- If the first included character of a template is one of the Wiki markup characters :;*#, then it is processed as though it is at the beginning of a line (even when the template tag is not). This allows the creation of various kinds of lists in templates where the template may not always be in the correct place for a list. To avoid this effect use <nowiki>#</nowiki> or a numeric character reference (Templat:Mlw) or HTML entity such as : for a colon. This NCR is also useful in conjunction with definition lists.
- When a page called for transclusion is a redirect page, the redirect target is included instead.
- A page that consists of nothing but the transclusion of another page is similar to a redirect, with minor differences. This method can be used to create functional "double redirects", should a need for such arise.
- For debugging templates the following techniques are sometimes helpful
- using 'subst:' - substituting a template (rather than transcluding it) can show more clearly what is happening when the template is transcluded.
- using 'msgnw:' - this keyword (short for "message, nowiki") transcludes the wikitext of the template page, more or less, rather than the processed contents. it is not perfect: lists are rendered, comments are removed, and single newlines are replaced with spaces (which is particularly confounding when transcluding wikitext tables).
Transclusion {{msgnw demo}} |
Substitution {{subst:msgnw demo}} |
Message, no wiki {{msgnw:msgnw demo}} | |
---|---|---|---|
Templat:Msgnw demo |
jkl mno |
[[:Templat:Msgnw demo]] |
Click the edit link for this section to see how the substituted section is different.
Template-like constructions
[sunting | sunting sumber]Any Wikimedia page can be transcluded, and this allows for constructions that are not technically templates, but share some of the features of them.
Composite pages
[sunting | sunting sumber]The wikitext of a page may (partly or fully) consist of tags for the inclusion of component pages. The component pages are usually not in the template namespace, and are often full pages in their own right. Composite pages are intended to gather the material on them into a central location.
Examples are:
- m:Help:A simple composite example
- Wikipedia:Village pump with six component pages, e.g. Wikipedia:Village pump (technical)
- Daily a page like Wikipedia:Votes for deletion/Log/2005 May 31 where each component page consists of the discussion on the deletion of one Wikipedia page, e.g. Wikipedia:Votes for deletion/Sp3tt (for this day there are 75 of such component pages)
- m:Meta:Translation/Coordination, mainly containing
- [1] - rejection of composite page by Wikipedia
This allows the choice between viewing the component pages separately or together. Viewing a composite page is convenient when there are many small, related component pages, in that it allows an overview of all the components without the effort of following numerous links.
in general, each component page and the composite page are treated separately. While the actual changes on the component pages will be transcluded onto the composite page, the edit history, recent changes, page-watch settings, page protection, TOC, "what links here" link, and other Wikimedia features of the composite page do not reflect or affect the histories, watch settings, protection levels, what links here lists of the component pages. The composite page is a page in its own right. The talk page of a composite page is used to talk about the composition and the page in general, not the component pages, though it in turn could be a composite of the talk pages of the component pages.
Editing a section of a component page can be done directly from the composite page, see editing sections of included templates. After saving, one ends up at the page for the component page to which the section belongs.
On projects with the interlanguage link feature the composite page shows the combined interlanguage links of all component pages, hence possibly multiple links for one language or even for one page.
See also Wikipedia talk:Template namespace#transcluding prose.
Pages with a common section
[sunting | sunting sumber]When two pages need to discuss the same material in the same way, they can share a section. This involves creating a third page and transcluding that page onto both pages. This third page may be a page in its own right or a subpage of either of the other two, and if the first it may be placed in the same namespace as the other pages or in template namespace. Common sections like this should be marked with an explanatory header, and/or given a special layout, to inform the reader that this section of the page is in a different location. They can easily confuse editors and readers alike if they aren't.
Examples:
- m:Help:Editing sections of included templates (bincang, pautan balik, sunting)
- m:Help:Alphabetic order (bincang, pautan balik, sunting)
Repetition within a page
[sunting | sunting sumber]On pages where there is a lot of repetitive information - various kinds of lists, usually - it is sometimes useful to make a template which contains the repeating text, and then call that template multiple times. For example, Template:List of Languages calls Template:Lang def repeatedly with different parameters in order to generate the visible text.
Simple repetition of the same text be handled with repetition of a parameter in a single template: e.g. {{3x}}, where {{3x| howdy!}} produces Templat:3x.
There is no real looping functionality built into the Mediawiki software as of this time (see, however, {{for loop}}), but there are some tricks for mimicking them. For instance, repeatedly calling a template which repeatedly calls a different template can mimic a double loop (see e.g. Template:ld (pautan balik sunting), Template:l2d (pautan balik sunting), and Template:l3d (pautan balik sunting)). Templates can also be coerced into calling themselves (normally prohibited by the Mediawiki software past a single instance, to prevent infinite loops), by the artful use of redirects (see m:Template:Loop1 (backlinks, edit) See also m:Help:Recursive conversion of wikitext.
Common usages, tips and tricks
[sunting | sunting sumber]Templates as table pieces
[sunting | sunting sumber]Tables using wikitable syntax can have rows and cells provided by templates. For instance:
Table construction | Template add_row contains | Processed result |
---|---|---|
{| border="1" |a||b |- {{add_row}} |c||d |} |
|1||2 |- |
{| border="1" |a||b |- |1||2 |- |c||d |} |
This always works for wikitables, and will work for HTML tables if the server variable $wgUseTidy is set to true (it defaults to false, but many WikiMedia projects enable it).
Templates in different versions of MediaWiki
[sunting | sunting sumber]Version 1.7
[sunting | sunting sumber]- ParserFunctions were added. Before they were available, multiple assignments of parameters with the same name (and thus allowing parameter overrides) were ingeniously used to perform branching, e.g. in the now deleted en:Template:If defined.
Version 1.6
[sunting | sunting sumber]- More magic words and the parameter default mechanism were added.
- <noinclude> and <includeonly> (see above) were added.
Version 1.5
[sunting | sunting sumber]- More magic words were added.
Version 1.4
[sunting | sunting sumber]- Including the same template more than five times in the same page works from version 1.4, now on all Wikimedia sites. Also new was that subst can be used with parameters.
Version 1.3
[sunting | sunting sumber]- A specific template namespace is created. Templates are no longer stored in MediaWiki namespace.[4]
- See, among other things, default values of parameters. Starting with version 1.3 the prefix "msg:" is generally optional.
Version 1.2.6
[sunting | sunting sumber]- Templates and MediaWiki interface messages are both stored in MediaWiki namespace: make a page MediaWiki:mytemplate and refer to it with {{msg:mytemplate}}. In this version parameters are not possible.
- Compatibility with 1.3, in the sense of having the content in Template:mytemplate, is possible with a redirect from MediaWiki:mytemplate to Template:mytemplate on the 1.2.6 project.
Version 1. ..
[sunting | sunting sumber]- Special:BookSources generates a page with external links based on Wikipedia:Book sources by replacing MAGICNUMBER with the ISBN to be entered. To some extent, this is a precursor to templates.
Revision history of pages containing templates
[sunting | sunting sumber]Pages in the stored page history consist of wikitext with possible references to templates and images. When viewing an old version of a page, these refer to the current versions of the templates and images, if these still exist. Thus the former composite page is not reconstructed.
Other pages not primarily meant for direct viewing
[sunting | sunting sumber]Pages not primarily meant for direct viewing include, apart from templates:
- multilingual portal pages, see www
- CSS and JS pages, see Help:User style
- pages in the MediaWiki namespace, see Help:System message
- Wikipedia:Book sources, used by Special:Booksources
- m:Spam blacklist
See also
[sunting | sunting sumber]Help pages | Manual pages | Special pages |
---|---|---|
|
|
|
Notes
[sunting | sunting sumber]- ^ Namespaces from which transclusion is not allowed are specified on a wiki by the variable $wgNonincludableNamespaces
- ^ technically, these features are available on all wikipedia pages, but they have little use outside of transclusion, and so they are generally considered template features.
- ^ Beginning with Wikimedia version 1.6.
- ^ User:Template namespace initialisation script