Jump to content

Help:テンプレート

From mediawiki.org
This page is a translated version of the page Help:Templates and the translation is 64% complete.
Outdated translations are marked like this.
PD 注意: このページを編集すると、編集内容が CC0 のもとで公開されることに同意したと見なされます。詳細はパブリック・ドメインのヘルプ ページを参照してください。 PD

複数のページに含めたい共通テキストがある場合は、MediaWiki のテンプレート機能が役立ちます。 拡張機能 メディアファイル とは異なり、テンプレートのための中央リポジトリはありません。 テンプレートは新しく作成するか、既に完了した作業の重複を避けるために、他のウィキ、例えばウィキペディアからエクスポートして、その後対象のウィキにインポートできます。

基本的な使用法

テンプレートとは内容を他のページに参照読み込み (トランスクルード) できるよう設計された標準ウィキページです。命名規則により、テンプレート名は接頭辞「Template:」で始まり名前空間に紐付けされます。その他、他のウィキページのように作成することもできます。

To transclude a template, you used double open & close curly brackets {{template name}}.

テンプレートの最も簡単な使い方は以下の通りです: Template:Welcome という名前のページを以下の内容で作成します:

こんにちは! ウィキへようこそ。

はじめてのテンプレートが作成できました! 次に以下のコードを新しいページに挿入します:

{{Welcome}}

新しいページを表示したとき、{{Welcome}}と表示する代わりに「こんにちは!ウィキへようこそ」という文が表示されます。テンプレートの内容が他のページに参照読み込み、つまり表示先のページに統合されます。

任意ページの任意の位置に歓迎文{{Welcome}}を挿入することもできます。100ページで使用されていると仮定します。テンプレートの内容を次のように変更した場合:

こんにちは、皆さん! この素敵なウィキへようこそ。

その後、このテンプレートを使用した前出の100ページのどれかを開いて確認すると、元の文ではなく新しい文を表示します。各ページにテンプレートが参照読み込みされているため、この方法で100ページ分の内容を編集することなく、一括で変更できます。

これが基本的な仕組みです。参照読み込みにはさらにこの仕組みを強化してテンプレートをとても便利にする機能があります。

テンプレートを呼び出す方法

テンプレートは、他のページ内で以下のように使用します。

  • {{名前}} — 上記で説明したように、このテキスト (一般的には「テンプレート呼び出し」と呼ばれます) は、ページ名が Template:名前 となっているページの内容で 動的に 置換されます (「参照読み込み」(トランスクルージョン) と呼ばれるプロセス)。これはテンプレート呼び出しを含むページが 読み込まれる たびに行われます (つまり、ウィキの読者がそのページを閲覧するときに)。 テンプレート呼び出しはページのソースに残るため、その後のTemplate:名前への変更はテンプレート呼び出しを含むページ上に表示されます。 また、そのページはテンプレートへリンクしているページ(リンク元)に列挙されます。
  • {{subst:名前}} — この種類のテンプレート呼び出しが使用されると、それはテンプレート呼び出しを含むページが 保存される 時点での Template:名前 の内容の 静的なコピー に置換されます。 つまり、テンプレート呼び出しはTemplate:名前の内容のコピーに置換されます。 ページとテンプレートの間のリンクは維持されないので、互いに影響を与えることなくさらに編集できます。 事実上、この方法で置換することと単純に「手動で」ページのソースに入力することの間にはほとんど違いがありません。 詳細情報は Help:Subst展開 を参照してください。
  • {{safesubst:名前}} — これは、テンプレートが他のテンプレートやパーサー関数を呼び出す場合に再帰的な置換を許可するために導入されました。 詳細情報は Help:Subst展開 を参照してください。
  • {{msgnw:名前}} — これは、それを含むページが表示される際に、テンプレートの内容を生のウィキ構文として表示します (‎<nowiki> がするのと同じ方法)。 例えば、 {{msgnw:Template:Thankyou}} は以下のように表示します:

<noinclude> <languages/> </noinclude> '''感謝をこめて...''' {{{reason|{{{1}}}}}}。 {{{signature|{{{2}}}}}} より <noinclude> [[Category:Template examples{{#translation:}}|{{PAGENAME}}]] </noinclude>

実際は単にページ名を含む名前空間を指定することで、通常のwikiページをテンプレートとして使用することもできます。たとえば

  • {{Template:ページ名}} は「Template:Pagename」という名前のページを参照読み込みします ({{ページ名}} と同等)。
  • {{Talk:ページ名}} は「Talk:ページ名」という名前のページを参照読み込みします
  • {{:ページ名}} は「ページ名」という名前のページ (標準名前空間内) を参照読み込みします
    • {{subst::ページ名}} は「ページ名」という名前のページの内容に置換されます

指定された名前空間が存在しない場合は完全ページ名のテンプレートであると仮定されます。

  • {{Foo:Bar}} は Template:Foo:Bar を参照読み込みします

どの構文を使用するかにかかわらず、テンプレートの名前は現在のページに対して相対的にできます。 例えば、 {{/bar}} がページ foo で呼ばれた場合、ページ foo/bar を参照読み込みします。

動的に生成することもできます。 例えば、 {{ {{foo}} }} は Template:foo を呼び出し、結果を呼び出したい他のテンプレートの名前として解釈します。

パラメータ

MediaWikiは、参照読み込みの機能を豊富にするために、テンプレートを参照読み込みするときにパラメータを渡します。パラメータによって、テンプレートからさまざまな異なるコンテンツを生成したり、異なる挙動をさせる事ができます。

つぎのような、ちょっとした感謝の言葉を他の利用者のトークページに挿入したい場合


感謝をこめて... あなたの尽力に。 私 より


この感謝文には理由(この場合は「あなたの尽力に」)と署名(「私」)があります。目的はすべてのユーザーが理由にかかわらず他のユーザーに感謝できるようにする事です。

ノートがどこで使用されても同様に見えるようにするために、例えば Template:Thankyou というテンプレートを定義することができます。 利用者が他の利用者に感謝するときには、ノートは同様に見えるはずですが、その特定の内容(すなわち、理由と署名)は異なります。 そのため、パラメータとして渡す必要があります。 残りの要素を無視してボックスをフォーマットして画像を配置すると、テンプレートのコアコンテンツは次のようになります。

'''感謝をこめて...'''
{{{1}}}{{{2}}}より。

{{{1}}}{{{2}}}の使用には注意してください。これはテンプレートを使用したときに渡すパラメータをテンプレート内で識別するための使用法です。テンプレート内では各パラメータが3対のブラケット{{{ }}}に囲まれている、ということに注意してください。これは通常のテンプレート名の使用法とは異なります。

ページからテンプレートを呼び出すときは各パラメータ値を「パイプ」文字(|)で区切って記述します。MediaWikiはパラメータを名前なし、番号付き、名前付きという3通りの方法でテンプレートに渡すことができます。

名前なしパラメータ

名前なしパラメータを渡すには、パラメータを順番にリスト化してください。

{{Thankyou|あなたの尽力に|私}}

この場合は{{Thankyou}}テンプレートが{{{1}}}=あなたの尽力に{{{2}}}=私というパラメータを受け取って、次のように返します。


感謝をこめて... あなたの尽力に。 私 より


名前なしパラメータを渡す順番が動作に影響します。パラメータの順序を逆にしてみます。

{{Thankyou|私|あなたの尽力に}}

以下のように出力されます。


感謝をこめて... 私。 あなたの尽力に より


順番 ({{{1}}} など) によるパラメータの識別機能は名前なしパラメータだけで動作します。 ページが名前で識別した任意のパラメータは、以下に示すように、序数を使用してテンプレートにアクセスできなくなります。
テンプレートの名前なしパラメーターの引数の中に等号 (=) が現れた場合、そのパラメーターは誤って名前付きパラメーター (この文書で後述) と解釈され、等号の前の文をパラメーター名、その後の文を引数の値として扱ってしまう可能性があります。 これは外部リンクまたは属性を持つHTML要素を含める必要がある場合、よくある問題です (タスク T16235 を参照)。 この問題を回避するには、名前付きのパラメータを使用するか、次の節で説明するように番号付きのパラメータを使用します。

番号付きパラメータ

パラメータを渡すときに、番号によってパラメータを識別します:

{{Thankyou|2=私|1=あなたの友情に}}

今回、テンプレート{{Thankyou}}は、パラメータ{{{1}}}=あなたの友情に{{{2}}}=私を逆順で受け取り、出力結果は:


感謝をこめて... あなたの友情に。 私 より


これは、番号付きパラメータのいずれかに = の記号が含まれている場合にも便利です。
{{Thankyou|1=「=」を追加して頂いたことに|2=私}}

出力結果:


感謝をこめて... 「=」を追加して頂いたことに。 私 より

警告 警告: これは他のパラメータにもそれぞれ番号を付ける必要があります。

名前付きパラメータ

パラメータを渡す第3の方法として数字の代わりに名前を使用します。この場合はテンプレートの内容をこのように変更してください。

'''感謝をこめて...'''
{{{reason}}}。
{{{signature}}}より

テンプレート内で各パラメータを識別するために、数字の代わりに{{{reason}}}{{{signature}}}を使用しています。名前でパラメーターを渡すと、渡したときに各パラメータが識別されます。

{{Thankyou|signature=私|reason=ありのままのあなたに}}

この場合は{{Thankyou}}テンプレートが{{{reason}}}=ありのままのあなたに{{{signature}}}=私というパラメータを受け取って、次のように返します。


感謝をこめて... ありのままのあなたに。 私 より


名前付きパラメータは大文字・小文字を区別するため:

{{Thankyou|signature=私|Reason=ありのままのあなたに|reason=大文字と小文字の区別をしてくれて}}

出力結果:


感謝をこめて... 大文字と小文字の区別をしてくれて。 私 より


テンプレートに名前付きパラメータを使う利点は、パラメータを渡す順番が柔軟になることに加え、多数のパラメータを組み合わせてもテンプレートのコード読解がとても容易になることです。

スペースおよび改行は、名前付きパラメータの名前および値の最初と最後から自動的に取り除かれますが、名前なしパラメータでは維持されます。

名前付きと名前なしのパラメータを混ぜる

テンプレートがサポートしている場合、両方の種類のパラメータを1回の呼び出しの中で使用できます。

For example, {{Thankyou|supporting both parameter types|signature=Me}} results in:


感謝をこめて... supporting both parameter types。 Me より


Be careful when doing this, because it can result in conterintuitive results as unnamed parameter counts are based only on the unnamed parameters, not the named parameters. For example, {{Thankyou|Me|reason=supporting both parameter types}} results in:


感謝をこめて... supporting both parameter types。 {{{2}}} より


The template is coded to prefer the named parameter for the reason over the unnamed parameter, resulting in the "Me" being lost and no signature being given. This results in a default value of {{{2}}} being shown, as explained below.

既定値

パラメータを取るテンプレートなのに、このように引数を指定せずに参照読み込みすると:

{{Thankyou}}

上述の番号付きパラメータの例では次のようになります:


感謝をこめて... {{{1}}}。 {{{2}}} より


引数を渡さなかったため、テンプレートはパラメータのそれぞれの値の代わりにパラメータ自身を提示します。この場合、パラメータの既定値、つまり値を渡さなかった際に使用される値を定義すると有用かもしれません。例えばテンプレートの内容を以下のように変更します:

'''感謝をこめて...'''
{{{reason|すべてに}}}{{{signature|私}}}より。

{{{reason|すべてに}}} は、パラメータ {{{reason}}} に引数を指定しなかった場合の値を定義しており、その値として すべてに が使用されます。同様に {{{signature|私}}} では、パラメータ {{{signature}}} の既定値が になります。さて、いかなる引数も渡さずに再びテンプレートを参照読み込みすると、以下のようになります:


感謝をこめて... すべてに。 私 より


パラメータの値は空の文字列にできます。 例えば、 {{foo|bar=}} または {{foo|bar=|baz=qux}} では、fooテンプレートは bar パラメータが "" であるとみなします。 これはパラメータを完全に省略するのとは異なります。その場合には未定義のままとなり上述の既定値の仕組みが発動します。
If you need to treat an empty string the same way as a missing parameter, you can use a conditional operator through an extension like ParserFunctions. For instance, {{#if:{{{1|}}}|{{{1|}}}|undefined}} returns undefined if the parameter is either undefined or empty, while {{{1|undefined}}} does so only if the parameter is undefined.

多くの場合、パラメーターの代替名を指定するために、既定値が使用されます。 例えば {{{a|{{{b|}}} }}} の場合、テンプレートはまず「a」という名前のパラメーターを探します。 それが設定されていない場合、「b」という名前のパラメーターを使用します。 「a」も「b」も設定されていない場合、何も出力されません。

Passing parameters to other templates

If raw parameter syntax is generated by the above template call, and then passed through to another template, it is not interpreted as a parameter. This means that {{Thankyou2 }}, which just calls {{Thankyou }} with no parameters, does not work: {{thankyou2|everything|me}} -> 感謝をこめて... {{{1}}}。 {{{2}}} より .

You instead need to explicitly pass the parameter to the other template, i.e if {{Thankyou3 }} contains

{{thankyou|{{{1}}}|{{{2}}}}}}

then {{thankyou3|everything|me}} -> 感謝をこめて... everything。 me より } works properly.

This example does not preserve emptiness vs. undefinedness in parameter values - you would need more complicated syntax if you wanted to do that.


Empty vs undefined parameters

The {{t2demo|| a }} (refer to {{T2demo }} ), with a double pipe, sets the first parameter to an empty string instead of leaving it undefined. It produces the output start--middle- a -end, similar to how {{t2demo|1=|2= a }} results in start--middle- a -end. On the other hand, explicitly setting the parameter "2" to "a," results in the first unnamed parameter being left undefined:

{{t2demo|2= a }} results in start-{{{1}}}-middle- a -end

If the second parameter should not be trimmed, it must be unnamed.

Therefore, you can assign an empty string to the first parameter, but you cannot leave it undefined.

Making emptiness and undefinedness equivalent

Good template coding practices result in passing an empty string to a parameter working the same as not assigning any value. This makes things easier and more consistent.

For example, using p= can show that a template has a parameter "p" that doesn't have a value yet.

To make an empty string and an undefined value equivalent, use the following approaches:

  • Use {{{p|}}} exclusively instead of {{{p}}} or q where "q" is a non-empty value.
  • Use conditional checks like {{#if:{{{p|}}}|..{{{p}}}..|..}}, to ensure {{{p}}} is only used when it has a value.

If for some reason you want to treat undefined parameters differently from empty parameters or any other possible value you can compare the same parameter twice with different defaults, i.e {{#ifeq:{{{foo|bar}}|{{{Foo|baz}}}|parameter is undefined|parameter is defined}}.

名前なしパラメータで等号を使う

Unnamed parameters can include equals signs, but this must be done indirectly. Here are some methods using template:T1demo:

Default Value for Undefined Parameter

Assign a default value to an undefined parameter:

{{T1demo|{{{1| a=b }}}}}

This renders as: start a=b end.

Using the {{=}} parser function

Use a parser function that safely includes an equals sign:

{{T1demo| a{{=}}b }}

This renders as: start a=b end.

HTML Entities

Replace the equals sign with an HTML entity for display:

{{T1demo| a=b }}

This renders as: start a=b end.

This renders correctly without affecting the other parameters.

Handling unmatched curly and square brackets

Unmatched curly brackets ({{, }}) or square brackets ([[, ]]) must be inside nowiki tags or use HTML entities:

  • Rendering curly brackets have two options:
    • Use <nowiki>{{</nowiki> or &#123; for {
    • Use <nowiki>}}</nowiki> or &#125; for }.
  • Use &#91; for [ and &#93; for ].

Below are some examples:

Unmatched curly brackets
{{T1demo| <nowiki>{{</nowiki>content<nowiki>}}</nowiki> }}

This correctly renders the braces without breaking the template.

Unmatched square brackets
{{T1demo| text [link] more text }}

This correctly renders the braces without breaking the template.

This renders as: start text [link] more text end

Unmatched pairs not placed in nowiki tags either prevent template expansion or are taken as closing braces for the template call.

Below are some examples:

{{T1demo|abc]]def[[ghi}}

This will not expand correctly because of unmatched brackets.

The correct use:

{{T1demo|abc<nowiki>]]</nowiki>def<nowiki>[[</nowiki>ghi}}

This renders as: startabc]]def[[ghiend

Template-generated brackets

An alternate technique for passing arguments with unmatched brackets is to wrap them in another template. In that situation, (which exists with {{(( }} and {{)) }}) on this wiki), the unmatched brackets will be rendered literally, and not decoded as another template call. For example:

{{t1demo|{{((}}t1demo{{))}}}}

results in: start{{t1demo}}end

When substituting a template, template inclusions are parsed once when the subst happens (with the same caveats explained above) and then a second time when rendering the resulting wikitext. For example:

{{subst:((}}t1demo|foo}}

will expand on save to:

{{((}}t1demo|foo}}

which will then render as:

startfooend

If the wikitext generated via the first subst itself includes "subst:" syntax it will not be processed on the same save, but may be on the next save. This technique may be used to implement recursive substitutions that take multiple saves to evaluate.

Using pipes in parameter values

A parameter value cannot contain a pipe character (|), because it would be interpreted as the end of that parameter and the start of the next parameter. This can be worked around by using the parser function {{!}}, or the HTML entity &124;. The two methods of doing this have slightly different behavior, which can be relevant in some corner cases like when a template is producing wikitable syntax.

Example: {{T1demo|abc|def}} produces: startabcend

The "def" doesn't display because it is treated as part of another unnamed parameter, which the template does not use.

{{T1demo|abc{{!}}def}} produces: startabc|defend

The "def" displays properly.

{{T1demo|abc|def}} produces: startabc|defend

The "def" displays properly again.

Formatting template calls using extra parameters

Since templates ignore parameters they are passed but do not handle specifically, they can be used as a way of a adding extra whitespace or unused content to the template call.

For example:

{{template name|foo|bar|baz|mumble|quux}}

is equivalent to, assuming the template doesn't recognize SPACEN as a parameter name:

{{template name|SPACE1=
|foo|SPACE1=
|bar|SPACE2=Random stuff
|baz|SPACE3=
   |mumble|SPACE4=
  quux
}}

It is also possible to use the same name for each spacer (often the empty string), but this will populate Category:Pages using duplicate arguments in template calls, which many wikis prefer to keep empty to catch instances of user error.

This can be used to make the template render in a way similar to its output, like showing each row of w:Template:Chess position on its own like to make the wikitext also look like a chessboard.

Tracking parameter usage


It may be wise for a template to add a link or category to a page if a certain parameter or combination of parameters is used, to make if possible to easily determine what pages are using a given parameter, and thus what the impacts of changing that parameter in the template would be.

評価プロセス

これは高度な話題なので、必要ではない限りは読み飛ばして構いません。

一般に、テンプレート パラメーターはトークン化された後、そのままテンプレートに代入されます。 それらのパラメーターは、使用するまで評価されません。

This has a few consequences:

  1. If you have a Template:Start containing {{mytemplate, and a Template:End containing |foo=bar}}, and put {{start}}{{end}} on a page, mytemplate isn't transcluded, because tokens like "|" cannot be added by a template and keep their special meaning in templates. You can still use templates to control the name of a parameter or template, but you cannot split a template call amongst multiple templates.
  2. Dead-code elimination: If you make a template call like {{foo|{{DISPLAYTITLE:Bar}} }}, and Template:Foo does not contain {{{1}}}, then the DISPLAYTITLE is not used, since it is only evaluated when needed, and there is no parameter to substitute it into, so it is never evaluated. This usually comes into play when using Extension:ParserFunctions, and can be especially noticed when used in combination with the int: magic word that varies by user language. This isn't perfect, and in some cases even if the result of expanding a template is not used (because it is part of an if statement condition, for example), the process of evaluating it can still have side effects. For example, any links produced or other templates used will still be added to Special:WhatLinksHere even if they are not displayed.


Template parameters are pass by value, which means a template cannot modify its arguments. Parameters are treated as associative array, and parameter names are evaluated before parameter values. If the same parameter name is given more than once (either as named or unnamed), only the last instace is used, and the page is added to Category:Pages using duplicate arguments in template calls.

Template calls starting with the magic word subst: or safesubst: are evaluated in a separate first pass that only happens at save time, along with ~~~~ and links using the pipe trick. If they cannot be evaluated during the first pass, subst: calls are ignored, and safesubst: are treated as if a normal template.

Many but not all parser functions, parser tags and trancluded special pages are not directly included like templates but instead are replaced by a "strip marker". This means you cannot manipulate the results with parser functions like padleft: or similar functions from extensions, as they see the strip marker instead of the result of the parser function.

テンプレートの再帰

自身を呼び出すテンプレートによってMediaWikiが無限再帰に陥ることはありません。 MediaWiki は名前が太字 (ボールド体) のテンプレートを再帰 (recursion) しません。 例えば、Template:Aaaaの内容がa {{Aaaa}} zであれば、"a a Template loop detected: Template:Aaaa z z "と表示されます。

This safeguard precludes a potentially useful template idiom where a template self-normalizes its own calling arguments. In this forbidden example template:d can either be called {{d|20200311}} or {{d|y=2020|m=3|d=11}}. If called in the first manner, it recurses into itself with the second argument structure (obtained using string parser functions), which then follows a unified processing path.

{{#if:{{{1|}}}|{{d|y={{#sub:{{{1}}}|0|4}}|m={{#sub:{{{1}}}|4|2}}|d={{#sub:{{{1}}}|6|2}}}}|<!-- processing path with arguments y,m,d regardless of original call pattern -->}}

If template:d is modified to recurse into template:d/2 and template:d/2 is an identical manual copy of template:d this idiom works fine as the self-recursion safeguard operates dynamically and not statically.

A feasible way for the MediaWiki software to loosen the self-recursion rule would be to require that each recursive call have a distinct argument count from all previous active calls, at most once recursing with the argument count non-decreasing. That would provide a strong guarantee against infinite self-recursion while enabling useful idioms such as the one described here in a flexible manner.

If the processing path is of low complexity, a simple solution using only one template is to handle each calling convention on a separate if/else branch, duplicating the logic of the processing path within each case. If the processing path is more complex, each call-structure case can delegate to an implementation template with a unified call structure which provides the final template behaviour.

Tables in parameters

Since the pipe character (|) and equality sign (=) have different meanings in template calls and wikitables, in order to use table markup in the value of a template parameter one generally needs to "escape" those characters (i.e., protect them from interpretation as template markup) using special sequences:

  • the built-in magic word {{!}} provides an "escaped" version of | since MediaWiki 1.24
  • the built-in magic word {{=}} provides an "escaped" version of = since MediaWiki 1.39

Before the introduction of these magic words, many wikis used templates to accomplish the same things. On such a wiki, the magic words take precendence over the same-named templates.

Example table

A B C
A1 B1 C1
A2 B2 C1

Table code:

{| class=wikitable
!A!!B!!C
|-
|A1||B1||C1
|-
|A2||B2||C1
|}

Escaped table code:

{{{!}} class{{=}}wikitable
!A!!B!!C
{{!}}-
{{!}}A1{{!}}{{!}}B1{{!}}{{!}}C1
{{!}}-
{{!}}A2{{!}}{{!}}B2{{!}}{{!}}C2
{{!}}}

Note that the first left-brace ({) is interpreted as a literal left-brace character because it is immediately followed by the {{!}} magic word. Similarly, the last right-brace (}) is interpreted as a literal right-brace character because it is immediately preceeded by the same magic word. However, in some cases these brace characters do cause problems, so some wikis provide templates for escaping these characters, as well:

  • the template call {{(}} might provide an "escaped" version of {
  • the template call {{)}} might provide an "escaped" version of }

Some wikis go even further and provide other convenience templates like {{(!}}, {{!)}}, {{!!}}. On such a wiki, the code can be simplified a bit to this form:

{{(!}} class{{=}}wikitable
!A!!B!!C
{{!}}-
{{!}}A1{{!!}}B1{{!!}}C1
{{!}}-
{{!}}A2{{!!}}B2{{!!}}C2
{{!)}}

テンプレートの読み込みの制御

既定では、テンプレートの内容は直接表示したときも別のページから呼び出したときも完全に表示されます。 テンプレートのページは直接表示したとき、パラメータが何もないテンプレートと全く同じように表示されます。 テンプレートを正しく機能させるためにパラメータが必要な場合、パラメータがないことによってウィキテキスト構文がそのまま表示されたりエラーを引き起こすことになります。

For example:

  • If a parameter has no default value, it shows as the literal text {{{1}}}, indicating the template needs a parameter.
  • If a parameter has an empty default value (it is written as {{{1|}}}), it displays nothing, which achieves the intended effect but lacks clarity for self-documentation. Using a non-empty default value like <tvar name="1">{{{1|$1}}} could clarify a parameter's role, especially for templates involving images.
  • If a parameter without a default is passed to the #expr parser function, it results in an error message: "Expression error: unrecognized punctuation character '{'."
  • If a template creates a table, it's helpful for the template page to show the table's structure rather than the wikitext used to make it.To do this, the table syntax isn't enclosed in tags, and each table element includes both ‎<noinclude>...‎</noinclude> and ‎<includeonly>...‎</includeonly> parts where needed.

しかし、‎<noinclude>‎<includeonly>‎<onlyinclude>のタグを使用することでテンプレートのどの部分を表示し読み込むか制御できます。

‎<noinclude>‎</noinclude>の間にあるものはすべてページが直接閲覧されるときのみ表示され、呼び込みされる場合は表示されません。これは、すべてのページで展開されることを望まないテンプレートに文やコードを含ませたい場合に有用です。実行できる応用例は次の通りです:

  • テンプレート自体をカテゴリ化する際に使用するカテゴリ
  • 他言語版の類似したテンプレートへの言語間リンク
  • テンプレートの使用法の説明文 It's a common pattern on some wikis to use a template like {{Documentation }} to transclude the documentation from a subpage of the template. For example, Template:Void is documented at Template:Void/doc.

逆は‎<includeonly>です。‎<includeonly>‎</includeonly>の間のテキストは、テンプレートのページを直接開いて閲覧しても処理されず、ページがインクルードされたときのみ処理され表示されます。明確な応用例は下記を含みます。

  • テンプレートを含むページのカテゴリ割り当て注:この方法で一つのテンプレートが割り当てる複数のカテゴリを変更した場合でも、参照ページのカテゴリはすぐには更新されないことにご注意ください。ジョブ キュー によって処理されるからです。特定のページのカテゴリを強制的に更新するには、ページを編集モードで開き、何も修正しないまま保存し直します。
  • テンプレートのページ自体を閲覧しても、コードが処理されないようにします。パラメータを与えないとコードが処理されない仕組みのため、パラメータを与えられないままテンプレートが作動すると望ましくない結果をもたらします。

‎<noinclude>タグと‎<includeonly>タグの外側部分は(テンプレートページで直接閲覧していても、テンプレートが他ページで呼び出されていても)通常ページ同様に表示されます。 重視すべきは、2つのタグがどんな内容を挟んでいるかという点です。

‎<onlyinclude>タグの外側部分は読み込み内容に入っていません。 includeonlyのタグが付いた節でも、参照読み込みのときに処理の対象から外されるため、改めてonlyincludeのタグをつける必要があります。 要点は、このタグの内側の部分にのみあります。

For example, if a page like Help:Templates/onlyinclude demo has the wikitext:

abc<onlyinclude>def</onlyinclude>ghi<includeonly>jkl</includeonly>

The result of transcluding it is def.

これらのタグは入れ子にすることもできます。

以上、3種の部分埋め込みタグは処理、レンダリングされる内容のあらゆる組み換えを可能にします。 コメントも役割を与えられています。 Inclusion tags are respected when using {{subst:templatename}}, but they are not respected when using {{msgnw:templatename}} as that displays the raw wikitext without any processing.

Section transclusion

To transclude different sections of a template on different pages, you can wrap the content in onlyinclude tags and use an if statement on parameters to select which section.

Consider "Template:Example" with this wikitext:

== Section 1 ==
{{#ifeq:{{{1|1}}}|1|
Content of section one.
}}
{{#ifeq:{{{1|1}}}|1|
== Section 2 ==
Content of section two.
}}

This will render both sections on the example page itself, and allow other pages to transclude the first section with {{example|1}} and the second section with {{example|2}}.

Another approach is to use literal parameter syntax instead:

{{{section1|
== Section 1 ==
Content of section one.
}}}
{{{section2|
== Section 2 ==
Content of section two.
}}}

Transclude the first section with {{example|section2=}} and the second section with {{example|section1=}}. If neither parameter is used, then both sections will display.

A third approach is to use Labeled Section Transclusion.

テンプレートの整理

テンプレートが有効に使われるには、ユーザーにとってテンプレートが見つけやすく、利用法が理解できる必要があります。

以下の方法で見つけられます:

  1. 特別ページ > 全ページをクリックし、
  2. 名前空間: 一覧で Template を選択して表示をクリック。

使用法の情報を示すには、テンプレートページにこのような例を含めてください。

<noinclude>
== 使い方 ==
利用者を歓迎する記述:
{{Thankyou|reason=あなたの理由|signature=あなたの署名}}
</noinclude>

その後、ほかの編集者はこの例をコピー&ペーストして、テンプレートを使えるようにします。

While editing a page, a list of all templates used is available under the editing form, in a collapsible section titled "このページで使用されているテンプレート:" (also named "このプレビューで使用されているテンプレート:", or "この節で使用されているテンプレート:" depending on the context). This list provides a convenient link to the template's page, as well as information about its protection status. Redirected templates are shown in italics, with the redirect target added as a separate list item.

テンプレートへのリンク

テンプレートページはほかのウィキページ同様、リンクすることができます。一例としてTemplate:Navbarというリンクを作成するには、ウィキコードの [[Template:Navbar]] を使います。

多くのウィキでTemplate:Tlを使うと、「波カッコ」付きのウィキコード(参照読み込み形式)を明示するフォーマットにまとめたテンプレートを、実際に読み込まずにリンクを張ることができます。例えば {{tl|Navbar}} というコードを使うと、{{Navbar }} というリンクが生成できます。

この構造はテンプレートの説明文書、ヘルプページまたはトークページでテンプレートについて述べるとき、よく使用されます。 同じ効果を得るのに、{{[[Template:Navbar|Navbar]]}} も使用できますが、{{Tl }} のほうが入力する文字数は少なくてすみます。 Tl テンプレートが用意されている場合、どんなウィキでも文を「code」の要素または等幅フォントでレンダリングするとは限りません。 (このウィキのように) うまく作動しない場合は、似た名称のテンプレートが有効かもしれません。 例えば、このウィキの Template:Tl の "See also" 節を参照してください。

Template naming

The name of a template is case-sensitive excluding the first character.

You make redirects for alternate capitalizations. For example, if a template is named "AdminAbbr", you can create a redirect named "Adminabbr". This way, the template can be called with either {{AdminAbbr}} or {{adminabbr}}. If an editor prefers a mix of upper and lower case for clarity, they can use functions like lc or uc. For instance, instead of {{CURRENTINTERNETTIME}}, they could use {{ {{uc:CurrentInternetTime}} }}

Because template names are interpreted in the same way to the names of other pages, underscores are replaced with spaces, and any text after a number sign (what would be a anchor in a standard link) is ignored.

An underscore _ can be alternative to a blank space.

Possible uses of templates

Templates can be used for any situation in which one wants two or more pages to contain identical or similar content that is edited together rather than independently. They can be used to:

  • Provide structured elements on many pages, like infoboxes, maintenance templates, navigational boxes, etc.
  • Perform calculations used as a programming tool on various pages, like w:Template:Sum.
  • Build composite pages that display the content of multiple existing pages together, like w:WP:Village pump (all) which includes content from each section of the village pump. The content of these pages can either be shown individually, or together, but the revision history, watchlist, etc. will only pick up changes to the transcluded pages and the raw wikitext of the composite page itself, not implicit changes to the composite page.
  • Share some content between a few related pages. For example, the list at Help:Preferences#Beta features is duplicated at Beta Features#Current Beta Features. While on MediaWiki.org that is built using Extension:LabeledSectionTransclusion instead, it could have been done using a template.
  • Store content referenced multiple times on the same page, so it only has to be written and calculated once. For example w:Template:Cite Monumentenregister/URL is called twice by w:Template:Cite Monumentenregister in two different places, and using another template means the URL pattern only has to be written once in the base template.
  • Use templates as a programming element to generate a loop: if Template:A calls Template:B 10 times with different parameters, then that crudely simulates a for loop. If Template:B calls Template:C 10 times, then you have a nested loop of 100 calls of Template:C. But keep in mind that it is easy to run into the template limits when using templates as advanced programming constructs, and using Scribunto is generally clearer and easier to follow.

別のウィキへのコピー

It is possible, if allowed by the wiki configuration to transclude templates from other wikis. This configuration setting is disabled on Wikimedia wikis. Otherwise, you need to manually copy the template and its dependencies from the source wiki to the destination wiki to use it.

テンプレートはCSSかその他テンプレートを要するため、利用者はウィキからウィキへのテンプレート複製にトラブルを抱えることになります。以下の手順はほとんどのテンプレートで有効とされています。

MediaWiki のコード

新しいウィキでインポート権限(特にimportupload)がある場合:

  1. 元のウィキのSpecial:Exportに移動し、必要なすべてのテンプレートの完全な履歴を含む.xmlファイルを次のようにダウンロードします。
    • 大きなテキストボックスにテンプレートの名前を入力します(例:「Template:Welcome」)。大文字と特殊文字に特に注意してください。テンプレート名が正確でない場合、エクスポートは引き続き行われますが、.xmlファイルには予期されたデータが含まれません。
    • 「テンプレートを含める」を選択する。
    • 項目「完全な履歴は含めず、最新版のみを含める」を選択する。
    • 「書き出し」をクリック。
  2. 新しいウィキの Special:Import に移動して、.xml ファイルをアップロードします。

新しいウィキの取り込み権限を持ってない場合:

  1. もととなるウィキから複製したいテンプレートに移動します。編集画面に移動し、ウィキテキスト全体をコピーします。
  2. 新たなウィキにて、コピーしたテンプレートと同じ名称のページへ移動します。作成、編集を押してコピーしたソースを貼り付けします。各テンプレートの編集要約欄では、帰属用に複製元のページへリンクさせてください。
  3. 編集画面での複製元ウィキに戻り、編集欄の下にある「このページで使われているテンプレート」の一覧をご確認ください。そこに列挙されたテンプレート1件ごとに、上記の処理を繰り返します。また、一覧のテンプレートから呼び出されるテンプレートにも、それぞれ同じ処理が必要です。

上記で必要なコードすべての複写ができ、テンプレートの種類によってはこれで十分です。 Note that only page elements parsed in rendering the page get exported, consequently documentation subpages are not exported as part of this process. うまく動作しない場合は、編集ボックスの下にある「Pages transcluded onto the current version of this page:」の下に赤いリンクが表示されていないか確認してください。いずれかの場合には、上記の手順を繰り返しモジュール内のコードをコピーします。

他のウィキからテンプレートおよびそれにリンクするテンプレート群のインポートに成功したら、ご利用のウィキに適合するように、カスタマイズする部分を編集します。例えばロゴの変更、廃止したカテゴリあるいは赤字リンクの削除などが必要かもしれません。

拡張機能

テンプレートで多用される拡張機能には ParserFunctions があります。 Extension:ParserFunctions のページを開き、一覧にある機能のうち、先ほど複写したテンプレート内で使用しているものがないか確かめましょう。 もし見つかったら ParserFunctions 拡張機能をインストールする必要があります。 インストールの処理は、MediaWiki インストレーションのサーバーでシステム管理者権限が必要です。

テンプレート、特にウィキペディアのテンプレートで使用される可能性のあるもう一つの依存関係は、Luaです。テンプレートコードに {{#invoke: }} が含まれていれば、その良い兆候であるといえるでしょう。 このコードを見つけたら Scribunto 拡張機能をインストールするのですが、これには管理者権限が必要です。 インストールと使い方は、拡張機能のリンクを開いてページを参照してください (訳注: Luaも参照)。

CSS および JavaScript のコード

MediaWikiコードの他にも、テンプレートの多くでCSSを使い、JavaScriptに依拠して完全に機能するものもあります。もし複写したテンプレートが予想通りに機能しない場合には、原因はそこにあるのかもしれません。必要なCSSやJavaScriptをご利用のウィキに複写するには、通常、管理者権限が求められます。「MediaWiki:」名前空間のシステムメッセージを編集する必要があるからです。

  1. テンプレートの文内にCSSクラスが使われているかどうか確認(例: class="foobar")。元のウィキの「MediaWiki:Common.css」ないしは「MediaWiki:Monobook.css」の中にCSSクラスがある場合は、これらを複写先のウィキの「MediaWiki:Common.css」に複写、テンプレートが予想通りに作動するかどうか確認をお願いします。
  2. それでも複写したテンプレートが予想通りに作動しない場合には、元のウィキの「MediaWiki:Common.js」もしくは「MediaWiki:Monobook.js」にコードがないかどうか確かめます。コードが見つかったら、それらをテンプレートの複写先のウィキの「MediaWiki:Common.js」に複写することもできます。通常、信頼できる情報源からのみコードを複写することが良識的で、まず関連のある部分を特定するためにコードをウェブで検索してみましょう。コメントから、コードの各部分の機能を見極めるヒントが見つかるかもしれません。

Redirection

If a page uses a redirect as a template, the redirect is resolved before processing the template and the target is used instead. This won't work if the target doesn't exist (a broken redirect), or is itself a redirect (a double redirect).

A page that just includes another page as a template might look like a redirect, but there are several differences between them:

  • The header of the result displays the title of the page it came from.
  • No "Redirected from" message is shown.
  • Buttons like edit, watch, talk, history, "what links here," and "last modified" point to the referring page. To access the target page, use a section edit link and navigate from there.
  • Unless includeonly and/or noinclude tags are used, the referring page shares the same categories as the target page.
  • "Double redirects" work when one or both are this type of pseudo-redirect.
Embedding works on pages that support redirects and doesn't work on pages without it.

Parser functions

メインのページ: Help:Parser functions

MediaWiki also supports parser functions, which function similarly to templates but follow slightly different syntax:

  • Parser functions utilize a ":" instead of the initial "|".
  • An edit page does not display parser functions used on that page.
  • There is no "What links here" feature for parser functions to identify the pages where they are utilized.
  • Parser functions templates do not generally accept named parameters, so equal signs generally have no special significance. For example:
{{ #if: not blank | x=abc }} gives x=abc

関連項目

General template usage

Special constructs used in templates


Other relevant information

外部リンク