Aide:Modèle

De Didaquest
Aller à la navigationAller à la recherche

Dans MediaWiki, un modèle est une page qui peut être insérée dans une autre page par un processus appelé "transclusion".

Cette page ainsi que la suivante (Help:Advanced templates) fournissent un manuel de référence sur les modèles dans MediaWiki. Pour une introduction, voir A quick guide to templates.

Note : les modèles peuvent être utilisés pour contrôler le corps de la page, mais pas les marges (logo, barre latérale...). Ils sont aussi contrôlés par l'apparence choisie, l'éventuelle personnalisation utilisateur, et le contenu de l'espace de nom MediaWiki.

Généralités

L’espace de nom des modèles est l'espace avec le préfixe Template: (en français Modèle:). Une page dans cet espace de nom est appelé "modèle". Le contenu d'une telle page peut être fixe, dépendre de paramètre, ou de variables, et sert à être inclus dans d'autres pages. Sur ces pages d'aide, on utilise Template: comme nom pour l'espace des modèles, à adapter sur votre wiki.

La syntaxe pour insérer un modèle est {{Nom}}, ce que l'on appelle un lien d'inclusion ; par exemple, le code wiki {{Abc}} inclura la page Template:Abc dans la page actuelle.

Si la page "Modèle:Nom" n'existe pas, alors un lien rouge vers cette page sera créé en lieu et place de l'inclusion, permettant d'éditer le modèle. C'est un moyen de créer un modèle.

Si le Nom entre les accolades commence par un des autres espaces de nom, alors "Template:" n'est pas ajouté. Exemple :

  • {{Nom}} inclura la page "Template:Nom"
  • {{Aide:Nom}} inclura la page "Aide:Nom"
  • {{:Nom}} inclura la page "Nom"

Même s'il est possible d'inclure n'importe quelle page, inclure une page de l'espace modèle a certains avantages :

  • l'insertion est plus intuitive (pas de nom d'espace à taper) ;
  • la page est listée sur la liste des modèles en mode édition ;
  • quand un modèle est modifié, toutes les pages qui l'incluent sont rafraîchies dans le cache du serveur, alors que pour les autres espaces de nom, il faut manuellement purger la page.

Si une page de l'espace Image: ou Catégorie: est incluse, seule la description apparaît (la partie modifiable, voir Catégorie et Page d'image).

En revanche, inclure une page qui n'est pas dans l'espace de nom modèle peut servir à :

  • citer un message de l’espace de nom MediaWiki ;
  • faire des essais personnels avec des sous-pages de sa page utilisateur ;
  • subdiviser de longues listes en plus petits éléments, tous visibles sur une page principale.

Il est possible d'inclure un modèle qui inclut lui-même un autre modèle. Si un modèle s'inclut lui-même (directement ou indirectement), l'inclusion ne marchera qu'une fois pour chaque modèle. Par contre, cela ne s'applique pas aux redirections : pour inclure un modèle plus d'une fois, utilisez autant de redirections.

Une variable dans un modèle est évaluée par rapport à la page dans laquelle le modèle est inclus ; par exemple {{PAGENAME}} donnera le nom de la page qui inclut le modèle, pas le nom du modèle lui-même.

Une liste des modèles utilisés sur une page, avec les liens correspondants, est montrée en mode édition, sous la fenêtre d'édition.
Notes :

  • seuls les modèle dans l'espace de nom modèle sont montrés ;
  • même si une seule section est éditée, la liste complète est donnée ;
  • même si une ancienne version est éditée, la liste montre les modèles de la version courante ;
  • même en prévisualisation, la liste n'affiche que les modèles déjà sauvegardés.

Utilisation de modèles entre les projets

Un modèle ne marche que sur une page du même projet ; il n'est pas possible d'inclure un modèle par un lien interwiki. Il faut donc copier le modèle (ou l'exporter) et le mettre sur le projet désiré.

Paramètres

Il est possible d'inclure un modèle avec des paramètres ; le modèle est alors composé d'une partie immuable et d'une partie qui dépend de paramètres. Les paramètres peuvent soit disposer d'un nom, soit d'un numéro.

La syntaxe est la suivante :

  • Avec des paramètres numérotés :
    • Pour inclure le modèle Abc : {{Abc|argument1|argument2}}
    • Sur la page du modèle, les paramètres sont inclus avec {{{1}}}, {{{2}}}, etc.
  • Avec des paramètres nommés :
    • Pour inclure le modèle Abc : {{Abc|paramètre1=argument1|paramètre2=argument2}}
    • Sur la page du modèle, les paramètres sont inclus avec {{{paramètre1}}}, {{{paramètre2}}}, etc.

En résumé, les paramètres sont inclus entre trois accolades. Lors de l'inclusion, le modèle est inséré, mais les paramètres (entre trois accolades) sont remplacés par la valeur qui leur a été assignée.

Les espaces avant ou après un argument sont ignorées : {{t|a}}, {{t| a}} et {{t|a }} reviennent au même.

Un argument ne peut pas contenir de barre verticale, excepté dans les liens redirigés. Les arguments en surnombre sont ignorés.

Restrictions sur les valeurs des paramètres

  • Si un argument contient un signe égal, le nom du paramètre doit être mis explicitement (donc même s'il est numéroté). Par exemple, pour donner "abc=def" en argument, il faudra écrire {{t|1=abc=def}} et non pas {{t|abc=def}}.
  • Il n'est pas possible d'inclure un appel à un autre paramètre comme argument.
  • Un argument ne peut pas contenir deux accolades fermantes consécutives, ou alors elles doivent être incluses entre des balises "nowiki". Ceci ne s'applique pas aux variables.
  • Les barres verticales (sauf celles des liens redirigés) doivent être mises entre balises nowiki.
  • La variable localurl ne peut pas être incluse si elle contient une barre verticale. (exemple : {{localurl:Aide:Modèle|edit}})
  • Un argument peut être très long, voir Help:Long parameter demo.

Paramètres numérotés ou nommés ?

Avantages de numéroter les paramètres :

  • Il y a moins à taper et moins à mémoriser (à part l'ordre).
  • Il n'y a pas de nom à traduire, ce qui est pratique pour les projets multilingues.

Avantages de nommer les paramètres :

  • L'ordre des paramètres n'a pas d'importance
  • Le modèle est plus simple à comprendre

Mélange de paramètres nommés et numérotés

Si des paramètres numérotés et nommés sont mélangés dans les même modèle, les paramètres non nommés sont numérotés 1, 2, 3...

Disposition du lien vers le modèle

Pour une raison quelconque, on peut vouloir disposer le lien vers le modèle d'une certaine façon, par exemple pour qu'il apparaisse sous forme de tableau ; dans ce cas, il peut s'avérer utile d'utiliser des paramètres "inutiles" qui n'affecteront pas le rendu du modèle mais permettent de mettre en page. Exemple :

{{t3d   |a|b|c| 1
        |d|e|f| 2
        |g|h|i| 3
}} 

donne

Modèle:T3d

Effet d'un paramètre non défini

Si on suppose que le modèle B contienne un paramètre {{{p}}}, et qu'il soit inclus sur la page A sans que p soit défini ; après inclusion du modèle, le paramètre est toujours là. Il existe différentes possibilités :

Le paramètre n'est pas inclus dans l'appel d'un autre modèle
Il est inclus tel quel sur A ; si A est inclus sur une autre page, p ne sera pas compris comme un paramètre.
Le paramètre se trouve dans un appel à un modèle C
Dans ce cas, les deux premières accolades fermantes (sur les 3) sont comprises comme la fin de l'appel du modèle ; le reste (troisième accolade et reste du lien au modèle) sont interpétés en-dehors du modèle, et donc les éventuels paramètres supplémentaires sont perdus.

Selon les cas et les modèles utilisés, ceci peut empêcher le modèle de s'afficher correctement, ou bien créer un résultat erroné, mais aussi ne pas affecter l'affichage. Il est possible de créer un modèle prenant en compte le cas où le paramètre n'est pas défini, voir sur la deuxième page.

Page du modèle

Le texte affiché sur la page du modèle est identique au résultat lorsque le modèle est appelé sans paramètres sur une autre page. Cependant, lors de l'appel d'un autre modèle sur cette page, la page du modèle peut être difficile à comprendre ; la page de discussion est utilisée pour cela.

Page de discussion associée

La page du modèle sert à définir le modèle, et la page de discussion sert souvent à expliquer le modèle (utilité, utilisation, ordre des paramètres, exemples, etc.), puis aux discussions le concernant.

Une valeur de paramètre dépendant de paramètres

NdT : le traducteur n'est pas sûr de ce paragraphe, voir Help:Template#A_parameter_value_depending_on_parameters.
Le code du modèle t2 est : start-{{{1}}}-middle-{{{2}}}-end.
Comme mentionné ci-dessus, si un paramètre est laissé indéfini, le paramètre entre triple accolades dans le résultat n'est pas considéré comme un paramètre si il est appelé par un modèle venant d'une autre page ; si ça se produit, ne pas oublier la valeur du paramètre mais spécifiez celui-ci en termes de paramètre dans la page qui appelle. Comparez :

La plus simple façon d'exprimer une valeur de paramètre en termes de paramètre est d'utiliser le même nom est d'utiliser le même nom et d'utiliser le signe "égal", par exemple {{Lan is|lr=af|le={{{le}}}}}.

Remarques

{{t2||a}} signifie que le premier paramètre équivaut à une chaine de caractères vide plutôt que de laisser celui-ci indéfini et donne Modèle:T2. En traitant le second paramètre non nommé comme un paramètre avec le nom "2", le premier paramètre non nommé peut rester indéfini, par exemple {{t2|2=a}} donne Modèle:T2.

If the parameter is used in a tag like <font size> the default text may give invalid code that is conveniently ignored, rather than resulting in perhaps ugly code being rendered (but this may depend on the browser). See e.g. Template talk:Fontsize.

Les noms de paramètres (contrairement aux noms de modèles) sont sensibles à la casse, même pour la première lettre, et les espaces sont distingués des underscores. La chaine vide est aussi un nom de paramètre valide, voir Template:T empty string as parameter name.

Le paramètre 02 est distingué du paramètre 2 : en utilisant le modèle t pl0 (code : {{{1}}}{{{2}}}{{{02}}}), {{t pl0|5|6|7}} donne Modèle:T pl0.

Notez également que les paramètres dans l'espace de nom MediaWiki (messages de l'interface) sont écrit différement : $1, $2, etc.
Voir Meta-Wikimedia:MediaWiki namespace text.

Signe égal dans les valeurs des paramètres

Quand la valeur d'un paramètre contient un signe "égal", le nom du paramètre doit apparaître explicitement, sinon la partie avant le signe égal est considérée comme le nom du paramètre. Si cela arrive par accident, ce paramètre est comme inutilisé.

Exemple : {{TTT|a=b|c}} (code : [[:Modèle:TTT]]) donne Modèle:TTT (le paramètre inutilisé a prend comme valeur b, the first parameter value for which no parameter name is specified is assigned to the parameter with the implicit name "1" — it reads like so: Use template TTT, assign "b" to the perameter "a", use the value "c" for your first implicit perameter {{{1}}}.), while {{TTT|1=a=b|2=c}} gives Modèle:TTT (the first parameter is assigned the value "a=b" — it reads like so: Use template TTT, assign "a=b" to the expressed parameter "1", assign "c" to the expressed parameter "2"). In this case, if template TTT had a perameter {{{3}}}, {{TTT|1=a=b|2=c|d}}, "d" would be assigned to "3" as first implicit parameter without a value.

The same applies if a parameter value depends on a parameter, and may therefore contain an equals sign. Compare:

Préfixes spéciaux

msgnw =

Le préfixe msgnw (pour "message, nowiki") est utilisé pour afficher le texte wiki d'un modèle d'une autre page qui n'a pas été interprété (le même affichage que vous verriez si vous éditiez la page). Les listes numérotées ou non numérotées font exception : elles sont rendues comme listes au lieu d'afficher les signes # ou *. Les valeurs des paramètres sont ignorées.

Exemples:

Template:en

  • {{msgnw:en}} donne {{Indication de langue|anglais|en|texte={{{texte|}}}}}<noinclude>

{{/Documentation}} </noinclude>

  • {{en}} donne (en)

Template:t2

  • {{msgnw:t2|a|b}} donne [[:Modèle:T2]]
  • {{t2|a|b}} donne Modèle:T2

Template:Numbered list demo

{{msgnw:Numbered list demo}} donne: [[:Modèle:Numbered list demo]]

{{Numbered list demo}} donne: Modèle:Numbered list demo

La fenêtre d'édition montre :

#Amsterdam
#Rotterdam
#The Hague

Lien pour modifier un modèle

Lorsque l'on se trouve dans la page d'édition d'un article, une liste des modèles qui y sont utilisées est disponible (tout en bas avec le skin monobook). Il suffit de cliquer dessus pour accéder à la page du modèle.

Il est plus pratique d'inclure un lien vers la page d'édition directement dans le modèle, ce qui affichera les liens sur la page appellante.

Since these edit links are similar for various templates, it can be made a template itself, with the name of the template as parameter. See e.g. en:template:edit and en:Train.

On Meta there are:

For editing a template ({{{1}}} is the name without prefix):

For editing any file ({{{1}}} is the full page name):

For a template containing only one paragraph or less, without links or images, one can also make the whole contents link to the edit page, see Modèle:Timc.

This is e.g. convenient for editing an individual entry in a table, without having to search in the wikitext of the table.

Aide:Editing sections of included templates

Usage

Templates are useful for any text for which one wants a copy in two or more pages, and there is no need for each copy to be edited independently, to adapt it to the page it is in. Since parameters can be used, versions may to that extent even be different, and parameter values can be edited independently for each. Templates are not only convenient, but they can also "force" a useful uniformity. See also advantages of subprograms.

Typical applications are:

Various combinations are possible. E.g., the last two could be combined, so that e.g. every language version of Wikipedia has the same Infobox Countries template (for each project a copy, because the template mechanism can not import across projects), which has parameters for the data, and refers to templates with translations of standard terms.

See also Help:Advanced templates.

Navigational templates

A common, simple type of navigational template in a hierarchy of pages is one with the names, with links, of a parent page and child pages. It is placed on all the pages it lists. Thus a page that is not at the top or bottom of the hierarchy has two templates, one with its parent and siblings, and one with its children.

Variations also occur, such as pages having two parents, etc.

Self links do not give any complication: they are neatly displayed in bold and not as link. However, templates should have the correct page names and not rely on redirecting, since the feature does not work in that case.

A navigational template may also just allow going forward and backward in a linear sequence, e.g. en:Template:Pope. For the predecessor of the first and the successor of the last a message like "none" can be used. This is not applicable in the case of a cycle, such as the days of the week.

Composite pages

The wikitext of a page may (partly or fully) consist of tags for the inclusion of component pages. The "templates" are not necessarily in the template namespace, and may be more or less self-contained pages by themselves. An advantage of putting the components in the template namespace is that they are then included in the list of templates used on the composite page, all with links, on its edit page. On the other hand, the component page may, by itself, be of a nature that it belongs in e.g. the main namespace, while the prefix would suggest otherwise; also the prefix would clutter the pagename.

Examples are:

This allows the user the choice between viewing the component pages separately or combinedly. One may want to view a page separately if one has a slow connection; also sometimes people have sentimental reasons for having a separate page about a topic, e.g. a village. Viewing the combined page is much more convenient if there are many small component pages; even if a subbtopic page does not provide additional info, if it exists anyway, and is linked to, it is useful to display the content (making clear that the whole content is shown), it saves the trouble of checking the contents by following the link.

In the latter case the search function of the browser can be used for searching in the combined page. Similar to the section editing feature, it allows editing a component page; however, there is no possibility to have the combined wikitext in the edit box.

Edit history, recent changes, watching pages, and "what links here" work separately for the component pages and the composition page, not for the composite page. Related changes works for the component pages and for the composite page. Page protection can be set for selected component pages and for the composition page, not directly for the composite page.

The talk page of a composition page is used to talk about the composition and the page in general, and could in addition be a composite page of the talk pages of the component pages.

A composite page has an integrated TOC and section numbering; the numbering is not reset for each component page.

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.

For easy access to the component pages, links to them on the composite page (for example by self-links on the component pages) are convenient. Alternatively, access is through section editing, or, if the component pages are in the template namespace, through the list of templates called from the composite page, at its edit page.

Conversely, for easy access from a component page to the composite page(s) that call(s) it (if there are not too many of them) it is convenient to link the component page to them (on a composite page one becomes a self-link).

See also w:en:Wikipedia talk:Template namespace#transcluding prose.

Pages with a common section

A section on the relationship of the subjects A and B, or a subtopic equally relevant for A as for B, can be put both in page A and in page B, by making it a separate page C, called as a template from A and B.

Remarks:

  • For readers reading both A and B, it is useful that the duplication is indicated by a message or a special lay-out; otherwise it is confusing and inconvenient. One can for example use Modèle:Tim: Modèle:Common section
  • After saving one ends up viewing the template page. For easy access to the calling pages it is convenient to link the called page to them (on a calling page one becomes a self-link). This may well be integrated in the message about the duplication. It is even more convenient than the two-step link as shown above.
  • The section level of the embedded section(s) has to be the same in each embedding page. The same applies to lay-out and style.
  • Pages like C can be put in
    • the same namespace as A and B; advantage:
      • the kind of content of C is the same as that of A and B
    • the template namespace; advantages:
      • C appears in the list of templates called from A and B, at their edit pages
      • C by itself may not satisfy the standards for pages in the namespace of A and B, such as providing context (however, the message about the duplication explains it)

Examples:

For various remarks which also apply here, see also the previous section.

Repetition within a page

For a succession of similar pieces of content, as in a list, a computer program would use a loop. What comes closest in MediaWiki is putting the loop body in a template, and calling the template repeatedly, usually with a varying parameter value. This is somewhat primitive for a loop:

  • instead of "for i=1 to 5" we need to enumerate the values 1, 2, 3, 4, 5; on the other hand, this gives the versatility to use just as easily less regular values such as de, en, fr (collection-controlled loop).
  • repetition of code is minimized by the template, but the template call itself has to be repeated each time (but see also the next section)

Example:

  • Template:List of Languages - the "loop body" is in Template:Lang def; compared with putting the content of the latter directly in the list the advantage is that the variable part (the value of "code") occurs once each time in the code, although it is used twice. This is important because the fixed part of the list item code can be copied while the variable part is typically inserted manually.

For repetition of the same text the loop body can be a parameter, e.g. Template:X5 (see list).

A double loop is achieved by a second template that repeatedly calls the first. Similarly for a triple loop, etc. See e.g. w:en:Template:Ld, w:en:Template:L2d, and w:en:Template:L3d.

An example where the same template is used for different loop levels is Template:Loop 2. Because the software has a built-in protection against infinite nesting, a redirect is used for each level. The number of levels that the template can handle is determined by the number of parameters specified in the two template calls it comprises (because going up a level requires an extra parameter) and the number of existing redirects.

Similarly Template:Lanlp 1 is used for both the inner and the outer of a double loop. Adding an item (here a language) adds to each row and also adds an extra row.

Providing effective repetition without repetition of similar template calls in the wikitext

A technique for repetition of similar template calls without actually putting this list in the wikitext is demonstrated in m:Template:List of template calls. For an arbitrary template with up to three nameless parameters, it is equivalent to calling the template repeatedly, with the first parameter varying, and the possible other parameters fixed: one specifies the name, the values of the fixed parameters, and the list of values the first parameter should have in consecutive template calls, with a sequential number each, and ending with "end". The technique requires redirects like Template:List of template calls 3, as many as the maximum number of repetitions.

If e.g. the second parameter varies, or two parameters, then a similar template can be made, but each version requires its own set of redirects.

Example Modèle:Ut1:

{{List of template calls|t2|constant||abc|1|def|2|ghi|end|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}

gives:

Modèle:List of template calls

The empty parameters are needed in accordance with the maximum number of parameters the repeated template can have (currently three) and the maximum number of repetitions. Putting more empty parameters than needed at the end does not matter, but the number of empty parameters in the beginning of the list should be correct.

Images in templates

New: In a template, image code parameters can contain template parameters, e.g.

{{timgi|wiki|50|small}} {{timgi|wiki|100|medium}} {{timgi|wiki|200|large}}
{{timg1|st|50|pqr}} {{timg1|st|100|st}}

using Modèle:Tcw and Modèle:Tcw

donne

Modèle:Timgi Modèle:Timgi Modèle:Timgi Modèle:Timg1 Modèle:Timg1

For cases for which an image is not applicable or available, use a dummy image such as w:en:Image:No image.png.

For an image in a template that should be different for each page in which the template occurs, there are also the following possibilities:

  • a parameter value can contain the whole image code: {{t|[[Image:Tst.png|50px|bullet]]}} gives Erreur de script : le module « traduction » n’existe pas.
  • in projects where external images can be embedded, the url of the image can be a parameter: {{t|http://meta.wikimedia.org/upload/2/27/Tst.png}} gives Erreur de script : le module « traduction » n’existe pas.
  • the image is given a name of the form prefix{{PAGENAME}}suffix (with a suffix, consisting of the file name extension and possibly more, and possibly also a prefix). See examples below. Note that there is little flexibility: changing the name of a page in which the template occurs requires uploading the image again, with the corresponding name.

Internal links

In the case of an internal link in a template with the target depending on a parameter, and in the case of a link with the target depending on a template, existence detection works as usual.

Examples:

Interwiki links

Templates can contain interwiki links; this normally means all pages using the template will have the interwiki, which is usually a bad thing unless some fancy footwork is done. To link just the templates across wikis, use the <noinclude> tag. For example:

<noinclude>
[[de:Vorlage:Korrekter Titel]]
[[en:Template:Wrongtitle]]
[[es:Plantilla:Título erróneo]]
[[fr:Modèle:titre incorrect]]
</noinclude>

See also below.

External links

With external link style much is possible. A blank space in a parameter value or template content that is substituted in a URL is not taken as ending the URL, but converted to %20.

Examples:

However, a URL can not be composed of:

  • a first part in a parameter and a second part added by the template (although we have seen above that reversed it works: a second part in a parameter and a first part prefixed by the template)
  • a first part in a template and a second part after the template (although we have seen above that reversed it works: the second part in a template and the first part before the template)

Example of first restriction:

Examples of second restriction:

  • [{{th}}add at the end] Modèle:Ut1} gives [[[:Modèle:Th]]add at the end]
  • "{{th}}add at the end" gives "Modèle:Thadd at the end"

Navigational images

The following applies in projects where external images can be embedded.

Examples where the label contains an image and depends on the parameter or template:

With external link style:

Notes:

  • the c and d are used to show the more general case, without them the label is instead of contains an image, with perhaps [[help:link|{{timgurl}}]] giving [[help:link|Modèle:Timgurl]] the more useful kind.
  • the target can be made variable like above.


EasyTimeline code with a template parameter is not allowed

Discussion modèle:Etl


Noinclude and includeonly

Anything between <noinclude> and </noinclude> will be processed and displayed only when the page is being viewed directly, not included. Possible applications are:

  • categorising templates
  • interlanguage links to similar templates in other languages (Otherwise such a link appears in the edge of the page that includes the template, giving the impression that the link is to a version in the other language of the referring page instead of the template. The link label depends only on the sister project that is linked to, not on the page; it is set in the configuration of the project, typically it is the name of the language in that language. The target is only shown in the hover box and the status bar, depending on the browser.) - see also above.
  • pages in the MediaWiki namespace
  • explanatory text about how to use the template

The converse is <includeonly>. Text between <includeonly> and </includeonly> will be processed and displayed only when the page is being included. The obvious application is:

  • Adding all pages containing a given template to a category

Note that the usual update problems apply -- if you change the categories inside a template, the categories of the referring pages won't be updated until those pages are edited.

A category tag in a template; caching problem

If a template contains the code indicating that it is in a category, this does not only put that template in the category, but also the pages that include the template. Thus this is typically not applied to categorize templates, but to conveniently put pages in a category, based on the template they use. For example, this page includes Template:H:h and as a result is in Category:English documentation.

The page that contains the template correctly lists the categories to which it belongs. However, adding or deleting a category tag in the template does not add or delete the listings on the category page of pages that use the template, until some edit is made in the page that uses the template.

In other words:

  • lists of categories a page is in, are up-to-date
  • lists of pages in a category are based on the situation just after the last edit of the pages

Since adding or removing a category or template tag is obviously an edit there is only a complication when a page is indirectly added to or deleted from a category, through a change in a template the page uses.

To refresh category pages with respect to the listing of a particular page (adding or deleting the entry), a null edit can be applied to that page: just applying section edit and saving without changes.

Thus, a basic principle of templates, that changing the contents of a template automatically changes the pages that contain the template, does not extend to these pages being correctly listed on category pages. It still works, with a delay, for sets of pages which are all frequently edited anyway, for other purposes.

In other cases the principle is violated. What remains is that just making null edits is somewhat less cumbersome than changing category tags in each page.

In conclusion, adding or deleting a category tag in a template that is already in use should be avoided unless one is willing to make the null edits, or is willing to accept the (possibly very long) delay during which there is no consistency between the category pages and the category listing on the pages in the categories.

Newline in a template

A single newline works like a space, except in a list, there it breaks the list. Since templates containing a single paragraph or less could be called from a list, such templates should avoid single newlines.

Indentation or list code at the beginning of template content

Each of the characters :;*# at the beginning of template content is interpreted as if it is at the beginning of a line, unless nowiki tags are used:

abc{{p1|def}}ghi

abc{{p1|:def}}ghi

abc{{p1|;def}}ghi

abc{{p1|*def}}ghi

abc{{p1|#def}}ghi

give:

abcModèle:P1ghi

abcModèle:P1ghi

abcModèle:P1ghi

abcModèle:P1ghi

abcModèle:P1ghi

Caching

When a page in the Template namespace is edited, this automatically clears the cache of any pages which use that template. However, there are cases of indirect dependence where a page may still not be up-to-date, even after pressing Ctrl-F5 or similar. This is e.g. the case for pages (typically template talk pages) referring to en:Template:Tc, containing {{msgnw:{{PAGENAME}}}}, probably because the template page name referred to depends on a variable.

In order to update a page in such cases, use "action=purge", in a URL like https://didaquest.org/w/index.php?title=Aide:Mod%C3%A8le&action=purge

Server efficiency

When a template is edited, this automatically clears the cache of any pages which use that template. When a page is viewed, and the template in it has changed since last time the page was viewed, the HTML has to be reconstructed. (For logged-in users part of the HTML is different for each one, but if pages are mostly viewed by users who are not logged in, we can focus on them).

If a template is called from m pages and edited with a frequency f, while the pages are viewed with a frequency g, then the relative amount of work for rebuilding the page (as opposed to taking it from the cache) is per unit time:

    • if f<g: mf (for each time the template is edited, all pages have to be rebuilt)
    • if f>g: mg (each time a page is viewed, it has to be rebuilt)

If the frequency of changing the template varies, then for each time interval the amount of work has to be considered separately, and added. For example, if a template is called from 1000 pages, which are each viewed once a day, and if each month four edits in a row are made to the template, then the first causes a lot of work (1000 page refreshings) and the other three very little. Compare this with having the four edits spread over the month, i.e. every week a single edit is made to the template, this causes 1000 page refreshings every week.

subst

Putting "subst:" after the double opening braces causes an automatic conversion of wikitext when the referring page is saved: the subst tag is replaced by the wikitext of the template, with the parameter values substituted for the parameters. Subst can also be applied to a variable.

Example: {{subst:t2|[[a]]|[[image:tst.png]]}} Modèle:Ut1 will give the wikitext start-[[a]]-middle-[[image:tst.png]]-end, which is rendered just like {{t2|[[a]]|[[image:tst.png]]}}: Modèle:T2.

The replacement of a template tag by wikitext does not automatically work recursively: if the template calls another template, that tag is not replaced. One can subsequently add "subst:" again, thus doing manual recursion. This stepwise replacement can be useful for analyzing and explaining the working of templates calling other templates. See e.g. Template talk:Lop. It can also be used to create a page independent of templates, as a way to archive the rendered page and allow a permalink to it. See also bugzilla:2777, a request for a version of subst that automatically works recursively.

If you want to use a modified version of the resulting wikitext, you have to save the page with the unmodified wikitext first, then edit it, because when applying preview the subst code is not yet replaced in the edit box. In the edit summary of the temporary edit you can put "tmp" to indicate that you have not made an error but are still working on the page.

In the absence of parameters, an alternative that clutters the edit history less is, of course, copying the text from the edit box of the template page: then it can be edited before saving. Another method is using msgnw without saving, and copying the preview result into the edit box.

When subst is applied to a template:

  • a variable in the template is copied as such in the wikitext.
  • if the template call contains a variable, subst has to be applied to that variable as well, otherwise the first two closing braces of the parameter are interpreted as closing braces of the template.

Applying subst to a variable works like applying it to a template. E.g. a timestamp:

{{subst:CURRENTDAY}} {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}},    {{subst:CURRENTTIME}} (UTC)

giving:

10 March 2005,    08:23 (UTC)

One might be tempted to put this in a template, but then it would display the time of creation of the template; on the other hand, without the "subst:", it would give the time of loading the page with the timestamp. Neither is suitable for a timestamp, which should give the time of saving the new referral to the template (like ~~~~~ does).

Usage of a template through "subst:" does not show up in page histories, backlinks, etc.

Input box

Similar to applying "subst:" to include page A in page B, in the case that B does not exist yet and that A does not have parameters, is using an inputbox to create B, preloading A. A difference is that the wikitext can be edited before saving.

Rewriting a template that calls other templates in a self-contained form

If a template calls other templates one may want to rewrite it in a self-contained form (i.e., which does not need other templates) in order to use a copy of it in another project, without copying more templates.

For example, Modèle:Tcw, calling Modèle:Tcw, could be written "start-a-middle-{{{1}}}-end".

To do this semi-automatically, one cannot use subst without specifying a parameter, or with {{{1}}} as parameter: the result of that is like the template page t2a1 shows: Modèle:T2a1. In fact this is how the confusing rendering of a template page can be analysed.

Instead, one can apply subst with parameter "{{{1}.}.}." and obtain Modèle:T2 does not change the wikitext, which is rendered as just {{subst:H:f Aide|langs=|enname=Template}}, because the assumed template name contains braces, therefore the system concludes that the template does not exist.

Redirection

When a page called for inclusion is a redirect page, the redirect target is included instead. As usual, a double redirect does not work.

A page that consists of nothing else than the inclusion of another page as a template, shows similarities to a redirect to that other page, but also many differences, including:

  • the result has as header the name of the referring page
  • there is no redirect message
  • the buttons such as edit (for editing the whole page), watch, talk, history, "what links here", and "last modified", etc., refer to the referring page (to go to the target page, a section edit link can be used, from there the whole page can be accessed)
  • the referring page is in the same categories as the target page
  • "double redirects", with one or both being this kind of "pseudo-redirect", work.

Compare Help:Template namespace with Help:Template namespace - demo of alternative for redirect.

In a page that in turn includes such a referring page there is no difference.

Math tags

MediaWiki templates, variables and parameters cannot be used within math tags, see Template talk:Demo of attempt to use parameters within TeX.

A template looked upon as a subroutine

The wikitext of a page can be looked upon as a list of statements, in which case a template is a statement-type subroutine. Alternatively the wikitext is a string expression, in which case a template is a string function.

In the first view, a{{b}}c is a sequence of three statements, in the second a concatenation of three strings.

In both views, the b in {{a|b}} is a string expression: the value of an input parameter of type string; however, the expression involves only concatenation, not (as one might think in the second view) any string function.

A subroutine is selected based on evaluating the string expression for its name (so this is done at "run-time"), so the process seems like that of an interpreter.

The subroutine is the only programming construct / flow control construct.

There are no variables/constants or assignment statements, except in the framework of subroutine parameters. The only operator (see operator and operator (programming)) is concatenation.

A template itself can also be considered an operator, with the number of parameters being the arity.

Simple computations

Simple additions and multiplications can be performed based on concatenation, using the unary numeral system: when 2 is represented by 11 and 3 by 111, then concatenation gives 11111, which can be converted to 5, see Modèle:Tim and Modèle:Tim. An additional parameter allows not only to display the result 5, but also to call a template of choice with parameter 5.

Required auxiliary templates:

  • for every value m used as first operand a template calcm containing {{calc{{{2}}}{{{1}}}|m digits "1" |{{{3}}}}}, see e.g. Modèle:Tim
  • for every value n used as second operand for addition a template calcAn containing {{countn digits "1"{{{1}}}|{{{2}}}}}, see e.g. Modèle:Tim
  • for every value n used as second operand for multiplication a template calcBn containing {{countn times {{{1}}}|{{{2}}}}}, see e.g. Modèle:Tim
  • for every result r a template countr digits "1" containing {{{{{1}}}|r }}, see e.g. Modèle:Tim
  • the template that one wants to call with the result as parameter; if one just wants to display the result, or use it in a link target, or in an image tag, one uses Modèle:Tim

In view of the maximum length of 255 for page names, the maximum result can be 250.

Note that for any computation one can prepare an array with all results, but the amount of work to do that is proportional to the number of pairs (m,n) that one wants to use, while above the amount of work is only proportional to the sum of the number of values of m, n, and r.

Linking to a template

Unfortunately, when linking to a template instead of embedding it, transfer of parameters is not possible. This would be useful e.g. for the following:

  • for a given image, allow links to pages each showing the image in a particular size, without having prepared a separate page for each size
  • for given geo-coordinates, link to a page such as w:Template:Mapeu with links to maps of that location; this would be like the Special:Mapsources feature, e.g. http://kvaleberg.com/wiki/index.php/Special:Mapsources/59_55_N_10_44_E, proposed as an extension of MediaWiki, except that no computations are possible, but, on the other hand, it would enable multiple editable "Map sources pages" in the form of templates.
  • Template:Table of Wikimedia projects provides a table of links to similar pages on all Wikimedia projects, depending on a parameter, e.g. all main pages, or all lists of templates. A page would be convenient with links to various of such tables, made on the fly.

Coming close to this is a page with links like Template pages and Template talk pages. These section edit links would each give access to one table through the preview. The whole page could be very large in rendered form, because the whole page would never have to be rendered (although on saving the system would attempt to do so even if it not desired). As far as the variation of the parameter for the last part of the URLs is easy, such as just changing the namespace number, not all tables need to be present, one can change the parameter in the edit box and get the desired table on the fly by the preview.

Comparison of linking and embedding

Linking and embedding have in common:

  • if the page does not exist, a link to the edit page is shown; the links are identical if it is not a piped link; the link does not show parameters and does not show whether, after creation, the new page will be linked or embedded.
  • the name can depend on variables and parameters

Extra possibilities of linking:

  • the name can depend on the content of templates; this is not possible for the name of an embedded page, not even indirectly: the name can depend on a parameter, but a parameter value or name can also not depend on the content of a template
  • the page referred to can be outside the project (interwiki and external linking)

Extra possibility of embedding:

  • there can be parameters, i.e. a single page can have different rendered content; this is not possible with a link; note that embedding a page with a link still does not allow the linked page to depend on parameters (see also the previous section)

Other differences:

  • the syntax {{..}} or {{..|..|..}}, etc., versus [[..]] or [[..|..]], with the pipe character having a different meaning
  • obviously the difference between having the pages rendered combinedly or separately
  • for embedding the default namespace is the template namespace (for the main namespace prefix a colon), for linking the default is the main namespace; prefixing a colon is also allowed, so one can use {{NAMESPACE}}:...

Developing templates and template tags

When adding a parameter to a template that is in use, one can first adjust the tags, and then the template. During the work in progress, the template keeps working properly, but the new parameter becomes effective only at the end.

Alternatively, a new template name is used for the new version, and while adjusting template tags, the template name is also changed (for convenience, this is typically a small change, e.g. one letter or digit is added or changed). The advantage is that during the work in progress, the new parameter becomes effective on a page as soon as the tag has been adjusted. Also, the backlinks of both templates show the pages that are done and that still have to be done.

To accommodate future expansion of a template, involving more parameters, one can in advance add parameters with the empty string as their value to the template tags. If unnamed parameters are used, one does to have to plan in advance the meaning of the new parameters.

Backlinks

The backlinks feature in principle shows which pages call a given template. However:

  • Not more than 500 are listed; as a workaround, the set can be divided in subsets of not more than 500, each calling an auxiliary page which either calls or redirects to the main template; the backlinks of the auxiliary templates are together the pages that use the main template; one has to record the names of the auxiliary templates, because they are also part of the large set of backlinks of the main template, of which only 500 are shown. Alternatively, if it has advantages to use different versions of a template anyway, this also helps staying under the limit of 500.

For example, w:en:Template:Void has more than the 500 backlinks it shows. Thus it is not clear what templates use it (in fact, w:en:Template:Infobox CVG is one of them; that alone has more than 500 backlinks).

Templates in different versions of MediaWiki

Version 1.4

  • 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

  • See, among other things, [1].

Version 1.2.6

  • In MediaWiki version 1.2.6, 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.

In versions 1.3 and 1.4 the prefix "msg:" is optional and ignored.

From version 1.5 the tag {{msg:abc}} refers to Template:Msg:abc !

Revision history of pages containing templates

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.


Reserved template names

According to the MediaWiki help policy some template names are reserved for use in the Help namespace. This allows copying without modification of the wikitext of help pages across projects. This wikitext contains template tags of the form "{{h:rest of name }}" which allow project-specific content within help pages, using project-specific templates.

Template names referred to by such tags are reserved, follow the link Template:h:f to see the full template name in this project in the case that rest of name is "f ":

  • for English projects with case-insensitivity of the first character: template names starting with "Template:H:".
  • for other projects with case-insensitivity of the first character: template names starting with "Vorlage:H:" and "Modèle:H:", etc.
  • for projects with case-sensitivity of the first character: template names starting with "Template:h:", "Vorlage:h:", "Modèle:h:", etc.
  • for Hebrew "H:rest of name :" comes to the left of the Hebrew word for template תבנית , see he:Template:h:f, except that if rest of name is the empty string than ":H:" instead of "H::" comes to the left of תבנית , see he:Template:h:. The reserved names are those of which the canonical form of the URL starts with "http://he.wikipedia.org/wiki/%D7%AA%D7%91%D7%A0%D7%99%D7%AA:H:" and similar for the other Hebrew projects.

Note that "case-insensitivity of the first character" refers to the first character after the first colon, not after the second.


Examples

  • Modèle:Tiw - message
  • Modèle:Tiw
  • Modèle:Tiw
  • templates with many parameters and images depending on {{PAGENAME}}:
    • Modèle:Tiw
      • {{PAGENAME}}_flag_large.png
      • {{PAGENAME}}_coat_of_arms_large.png
      • Location{{PAGENAME}}.png
    • Modèle:Tiw
      • {{PAGENAME}}_flag_medium.png
      • {{PAGENAME}}_armoirie.png
      • Location{{PAGENAME}}.png
    • Modèle:Tiw
  • Modèle:Tiw - small, often used image
  • Modèle:Tiw - translation
  • Modèle:Tiw - intermediate template for translating the parameter names, containing e.g. "superficie = {{{area}}}"
  • Modèle:Tib
  • Modèle:Tib
  • Modèle:Tim - calls one of several templates, dependent on namespace
  • Modèle:Tiw - calls one of many templates, depending on pagename.
  • Modèle:Tiq - quote of the day - the content of the template is changed daily
  • Modèle:Tic - picture of the day - the pictures can be prepared in advance, because the template shows an image, depending on {{CURRENTYEAR}}, {{CURRENTMONTH}}, and {{CURRENTDAY}}, and, for the caption, calls one of many templates, depending on these and also on a parameter for the language; unlike the quote of the day above, the rendered image is changed at the fixed time of 0:00 UTC.
  • article of the day on the English Wikipedia: see list - included as a template on the main page.

See also



L'édition : vue générale

  1. Comment démarrer une page
  2. Nom de page
  3. Syntaxe wiki

Référencement

  1. Liens
  2. Lien redirigé
  3. Lien interwiki
  4. Variables
  5. URL
  6. Ancres
  7. Sous-page

Formatage

  1. Formules
  2. Tableaux
  3. HTML dans le code wiki
  4. Images et fichiers
  5. Page d'image
  6. Liste

Organisation

  1. Sections
  2. Modèles
  3. Catégories
  4. Redirections
  5. Renommer (déplacer) une page
  6. Espaces de nom

Économiser vos efforts

  1. Raccourcis d'édition
  2. Barre d'outils d'édition
  3. Éditeurs externes
  4. Mots magiques
  5. Export
  6. Import

Réparer les erreurs et le vandalisme

  1. Retour à une version précédente
  2. Tester
  3. Modérateur

Communication

  1. Résumé des modifications
  2. Page de discussion
  3. Conflit d'édition
  4. Modification mineure

Caractères spéciaux

  1. Caractères turcs
  2. Caractères roumains

Extensions

  1. Syntaxe WikiHiero
  2. Frise chronologique
  3. Boîte d'entrée