Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

KumaScript 入門

この翻訳は不完全です。英語から この記事を翻訳 してください。

草案
このページは完成していません。

概要

2012 年夏、MDN のシステムは Kuma という新しい wiki プラットフォームに切り替わりました。従来システムのテンプレート用言語であった DekiScriptKumaScript という新テンプレートシステムに置き換えられています。KumaScript は Node.js を使用して実装され、サーバーサイドの JavaScript によって供給されています。このページでは、KumaScript の使用方法、MindTouch からのテンプレートの移行方法について説明します。

協力者を募集しています。詳細については、次の項を参照してください: MindTouch からのコンテンツ移行の制限

KumaScript とは何ですか?

  • 複数の文書内の共通部分を再利用する為のもの。例えば、互換性情報を表示する小さなラベル、ページ内リンク、警告バナーなど。
  • 他の文書のコンテンツからドキュメントを生成する。
  • 外部 Web サイトへのリンクを設置したり、外部 Web サイト(※ Bugzilla など)の内容をインクルードする為のもの。

KumaScript で出来ない事

  • KumaScript では、フォーム送信内容を受け入れるような対話型スクリプトはサポートされていません。
  • KumaScript にはデータベースやファイルにアクセスしたり、情報を永続的に格納する仕組みはありません。
  • KumaScript ではログイン中のユーザ情報に基づくサイトの個人用設定などはサポートされません。
  • KumaScript はコンテンツとページのメタデータにのみアクセス可能であり、ユーザ情報にはアクセスできません。

基本

KumaScript は wiki エディタで許容されている 埋込み JavaScript テンプレート を記述する事によって動作します。テンプレート本体の編集は専用のページで行う事が可能であり、また、完成したテンプレートは各ページ編集時にテンプレート呼びだし用のマクロコードを記述する事によって使用する事が可能です。

テンプレート マクロ マクロの出力
<% for (var i = 0; i < $0; i++) { %>
Hello #<%= i %>
<% } %>
{{hello("3")}}
Hello #0
Hello #1
Hello #2

マクロの構文

KumaScript を用いて作成されたテンプレートのコンテンツは以下の様なマクロで呼び出す事が出来ます。

{{templateName("arg0", "arg1", ..., "argN")}}

マクロの構文は、以下の規則に基づいて構成されます。

  • マクロのコードは {{ より始まり、 }} で終わります。
  • マクロの最初の部分はテンプレートの名称です。「 /en-US/docs/Template:{name} 」 の様なパスの wiki ページがテンプレートとして動作します。テンプレートの作成及び編集には特権が必要であり、これは申請の後、信頼に足る編集者であると管理者が判断した場合にのみ付与されます。
  • テンプレートは引数を受け付けます。括弧内にカンマ区切りで複数の引数を記述する事ができます。
  • テンプレート内部では、渡されたパラメーターは変数 $0$1$2 としてマクロ内で利用可能です。第一引数は $0 となり、以下は昇順で続きます。
  • 数値以外の引数は引用符で囲まなくてはなりません。
  • パラメーター全体のリストも arguments としてテンプレート内部で使用可能です。

マクロの引数に JSON を用いる

もう一つの半実験的な機能がマクロで利用可能です。 最初のパラメーターのみの指定で JSON オブジェクトを取得可能です。

{{templateName({ "Alpha":"one", "Beta":["a","b","c"], "Foo":"http:\/\/mozilla.org\/" })}}

上記マクロではオブジェクトが一つ、パラメーターとして渡されています。先述の通りこのオブジェクトには $0 でアクセス可能です。そして、オブジェクトの各属性には

$0.Alpha //最初の属性、つまり文字列 "one"
$0.Beta
$0.Foo

この様にしてテンプレートコード内からアクセス可能する事が出来るのです。パラメータの単純なリストで行うのは難しい、或いは不可能なマクロパラメータで、複雑なデータ構造を表現することも可能です。

このパラメーターは、valid な JSON syntax でなくてはなりません。例えば先のコードでは、全てのスラッシュはバックスラッシュでエスケープされています。記述したコードが疑わしい場合は、JSON 部分をJSON バリデータにかけてみてください。

「 {{」を記述する方法

{{ 」はマクロコードの開始として解釈される為、単なる文字列としてのを表示を望んでこれを記述した場合に問題が起きます。この問題は、以下の様に最初の「 { 」をエスケープする事で回避可能です。

\{{translationInProgress}}

テンプレートの構文

KumaScript テンプレートは、以下の様な簡単なルールで記述可能であり、記述したテンプレートは組込 JavaScript テンプレートエンジンによって処理されます。

  • <% %> の外は出力ストリームとなり、テキストはそのまま表示されます。
  • JavaScript の変数や式は、以下のブロックを用いて出力ストリームに挿入可能です。
    • <%= expr %> — JavaScript の評価値を HTML エスケープして出力(※ <&lt; となる)
    • <%- expr %> — JavaScript の評価値をそのまま表示(※テンプレート内での動的なマークアップ作成に適している)
    • このブロック直下にセミコロンを含めるとエラーとなる(※エラーが発生する例: <%= expr; %>
  • <%%> の間は JavaScript として解釈される。即ち、ループ、条件文、関数などを含める事が可能。
  • <% %> ブロック内は出力ストリームに含まれない。ブロック内の変数などをブロック外で使用する場合は <%= %> を用いる。
    <% for (var i = 0; i < $0; i++) {
    	%>Hello #<%= i %><%
    } %>

    ※ 2 行目の行頭でそれまでのブロックが一旦閉じられ、出力ストリームに "Hello" と 変数 i を配置。行末から新しいブロックが開始、3 行目で for 文を閉じて、再びブロックが閉じられています。

  • EJSの構文の詳細については、上流モジュールのドキュメントでご確認ください。

Tips

日付と時刻

It's important to note that the standard JavaScript Date constructor is overridden by the KumaScript Date interface. You can create a JavaScript Date by calling the KumaScript date.now() or date.parse() function.

より高度な機能

KumaScript には前章までに紹介したもの以外に、より高度な機能もあります。

環境変数

When the wiki makes a call to the KumaScript service, it passes along some context on the current document that KumaScript makes available to templates as variables:

env.path
現在の wiki 文書(※テンプレートを記述したページ)への相対パス
env.url
現在の wiki 文書への 絶対 URL
env.id
現在の wiki 文書のユニーク ID
env.files
An array of the files attached to the current wiki document; each object in the array is as described under File objects below.
env.review_tags
An array of the review tags on the article ("technical", "editorial", etc.)
env.locale
現在の wiki 文書のロケール
env.title
現在の wiki 文書のタイトル
env.slug
現在の wiki 文書の URL スラッグ
env.tags
現在の wiki 文書に付与されたタグの名称のリスト
env.modified
現在の wiki 文書の最終更新日を示すタイムスタンプ
env.cache_control
Cache-Control header sent in the request for the current wiki document, useful in deciding whether to invalidate caches.

File objects

個々の file オブジェクトは以下の様なフィールドを持ちます。

title
添付ファイルのタイトル
description
現行版の添付ファイルに関する説明
filename
添付ファイルのファイル名
size
添付ファイルのサイズ(※単位 = bytes )
author
添付ファイルをアップロードした人のユーザ名
mime
添付ファイルの MIME type
url
添付ファイルの URL

Working with tag lists

The env.tags and env.review_tags variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions.

Looking to see if a specific tag is set

You can look to see if a specific tag exists on a page like this:

if (env.tags.indexOf("tag") !=1) {
  // The page has the tag "tag"
}
 
 
 
Iterating over all the tags on a page

You can also iterate over all the tags on a page, like this:

env.tag.forEach(function(tag) {
  // do whatever you need to do, such as:
  if (tag.indexOf("a") == 0) {
    // this tag starts with "a" - woohoo!
  }
});

API とモジュール

KumaScript では、ビルトインのユーティリティ API だけでなく、wiki 文書として編集可能なモジュール内で新規の API を定義する機能も提供されています。

ビルトインメソッド

This manually-maintained documentation is likely to fall out of date with the code. With that in mind, you can always check out the latest state of built-in APIs in the KumaScript source. But, here is a selection of useful methods exposed to templates:

md5(string)
与えられた文字列の MD5 16 進ダイジェストを返す
template("name", ["arg0", "arg1", ..., "argN"])
テンプレート名を第一引数、そのテンプレートに渡すパラメーター(配列)を第二引数として指定する。テンプレートの実行結果が返る。
テンプレート内から他のテンプレート読込みたい場合に、次の様な記述で利用可能です。
<%- template("warning", ["foo", "bar", "baz"]) %>
This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: <%- template("warning", [$1, $2, "baz"]) %>. If you need to call another template from within a block of code, do not use <% ... %>. Example: myvar = "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>";
require(name)
Loads another template as a module, any output is ignored. Anything assigned to module.exports in the template is returned.
Used in templates like so: <% var my_module = require('MyModule'); %>.
cacheFn(key, timeout, function_to_cache)
Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of env.cache_control to invalidate cache on no-cache, which can be sent by a logged-in user hitting shift-refresh.
request
Access to mikeal/request, a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things.

組込み API モジュール

現時点では kuma の API 用の名前空間には、「 kuma = { ... } 」の 1 つだけが定義されています。

kuma.htmlEscape(string)
文字列中の 「 & 」、「 < 」、「 > 」、「 " 」をそれぞれ「 &amp; 」、「 &lt; 」、「 &gt; 」、「 &quot; 」 に HTML エスケープします。
kuma.pageExists(path)
指定したパスにページが存在するかどうかを返す。長期間キャッシュされます。
kuma.include(path)
指定されたパスのページから、ページ内容をインクルードします。長期間キャッシュされます。

モジュールの作成

ビルトインメソッドの require() を用いると、テンプレート内の変数やメソッドを複数のテンプレート内で使用できるようにモジュール化する事が出来ます。モジュールの定義は、テンプレート内に以下の様に記述する事によって可能です。

<%
module.exports = {
    add: function (a, b) {
        return a + b;
    }
}
%>

このテンプレートを "/en-US/docs/Template:MathLib" として保存したとすると、このモジュール内の関数 add は、別のテンプレート内で以下の様に用いる事ができます。

<%
var math_lib = require("MathLib");
%>
The result of 2 + 2 = <%= math_lib.add(2, 2) %>

このテンプレートの出力は以下の様になるでしょう。

The result of 2 + 2 = 4

自動ロードモジュール

There are a set of modules editable as wiki templates that are automatically loaded and made available to every template. This set is defined in the configuration file for the KumaScript service - any changes to this requires an IT bug to edit configuration and a restart of the service.

For the most part, these attempt to provide stand-ins for legacy DekiScript features to ease template migration. But, going forward, these can be used to share common variables and methods between templates:

The best way to see the current state and offerings of these modules is to take a look at their source directly.

注記: You might notice that the DekiScript modules use a built-in method named buildAPI(), like so:

<% module.exports = buildAPI({
    StartsWith: function (str, sub_str) {
        return (''+str).indexOf(sub_str) === 0;
    }
}); %>

The reason for this is because DekiScript is case-insensitive when it comes to references to API methods, whereas JavaScript is strict about uppercase and lowercase in references. So, buildAPI() is a hack to try to cover common case variations in DekiScript calls found in legacy templates.

With that in mind, please do not use buildAPI() in new modules.

Tips and Caveats

Limitations of content migration from MindTouch

When we make the move to Kuma, we will migrate content from the old MindTouch-based wiki to the new Kuma-based one. This script will do some basic work to attempt to convert scripts. But, there are many common code patterns that migration can't fix.

So, this means that we'll need human intervention to carry template scripts over the rest of the way to being functional.

To find templates in need of review and repair, check here: https://developer-new.mozilla.org/en...eview/template

To find examples of templates that have already been repaired, check here: https://developer-new.mozilla.org/en...s/tag/ks-fixed

Check the template usage stats bug file attachments to help prioritize templates to fix. If you know your way around gzip and grep, this attachment (a 1.5mb tab-delimited file listing template/document pairs) can help tell you what templates are used on which pages.

As you repair templates, please uncheck the "Template" review checkbox and add the tag "ks-fixed", which will keep the above lists accurate.

You can also find templates in need of repair by simply browsing through wiki content and spotting where content looks garbled with code or otherwise incorrect. Editing the page should show you the name of a macro that's in need of help. You may also see scripting errors on pages, which should offer editing links to the templates causing issues.

Keyword Shortcut for quick template editing

もしあなたが KumaScript のテンプレートの作成や編集を頻繁に行う場合は、例えば以下のリンクをブックマークし、ショートカットキーワードを設定しておくと便利かもしれません。

名称 edit mdn template
URL https://developer-new.mozilla.org/en...mplate:%s$edit
ショートカットキーワード te

一度このショートカットを設定しておけば、テンプレートの名前をコピーして新しいタブを開き、"te [Ctrl-V][Return]" とする事でテンプレートの編集を開始する事ができます。This helps when a template is misbehaving, yet not badly enough to cause a scripting error message.

ロケール識別子の変更

MindTouch から Kuma へのシステム移行に伴い、幾つかのロケール識別子が変更となっています。

  • en -> en-US
  • cn -> zh-CN
  • zh_cn -> zh-CN
  • zh_tw -> zh-TW
  • pt -> pt-PT

我々に見落としがなければ、今後は既存のロケール識別子が変更される事はありません。これらのロケール識別子の変更は、DekiWIki のテンプレートを Kuma 用に変換する際に重要になります。

URL パターンの変更

全ての wiki 文書の URL は、 Kuma への移行に伴い以下の様に変更されました。

// 旧形式 (Dekiwiki)
{locale}/{slug}

// 旧形式 (MindTouch)
/{locale}/{slug}

// 新形式 (Kuma)
/{locale}/docs/{slug}

これらは以下の様に変更しなくてはなりません。

  • /en/JavaScript -> /en-US/docs/JavaScript
  • /de/JavaScript -> /de/docs/JavaScript
  • /ja/JavaScript -> /ja/docs/JavaScript

かかる変更に伴うリンク切れを回避する為に、システム側でも対策が講じられています。しかし極力これらは修正した方が良いでしょう。

訳注 :

この様な変更を一括して行うためのツールを個人で作成しました。MDN の編集時にソースモードよりソースコードをコピーアンドペーストし、ボタンを押す事で実行できます。更新時のみならず、新規翻訳時にもこのツールを用いる事により、システム変更に伴ういくつかの問題を修正したり、英語版の URL を日本語版のものに一括変換する事ができます。また、一部定型文の自動翻訳も行います。無保証 / パブリックドメインで公開します。是非ご利用下さい。

古い構文を新しい構文に置き換える事が主目的である為、古い構文について説明しているページ(※このページなど)に対してこれを用いると問題が発生する場合があります。その様なページでは用いないようにして下さい。

また、旧システムで編集時にのみ表示する目的で用いられていた div.comment を通常の HTML コメントに置き換える機能も備わっていますが、対象部分の内部に HTML タグが記述されている場合に誤変換を起こしてしまう問題があります。その際は Advanced Mode のチェックを解除して御利用下さい。

このツールを用いた場合は、必ず履歴ページで差分を表示し、問題が発生していないか確認して下さい。

User:ethertank

DekiScript との相違点

It's useful to note a few changes from templates in DekiScript, in case you encounter these in migrated content:

  • 従来の <span class="script"><span class="eval"> は不要となりました。
  • 従来のテンプレート読込みコードの先頭部分に必要だった template. または wiki.template 接頭辞は不要になりました
    (※: template.interwiki() -> interwiki())
  • 従来の冗長なシンタックス template({name}[, arguments]) も不要です。
  • テンプレート実行時の引数は引用符で括らなくてはならなくなりました。
    bug(123456)   // 従来のシステムでは引用符無しでも動作した
    
    bug("123456") // Kuma では引用符が必須となった
    Unless you are calling the template from within another template, and the argument is one of the passed-in args like $1 in this example: template("LXRSearch", ["ident", "i", $1]).

キャッシュ

KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged in user, you have two options to force a page to be regenerated, in case you notice issues with scripting:

  • Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a Cache-Control: max-age=0 header.
  • Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a Cache-Control: no-cache header.

クックブック

This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents.

Force templates used on a page to be reloaded

It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself.

「不明なエラー」からの回復

ページ読込時に、時折、このようなスクリプティング・メッセージが表示される事があります。

Kumascript service failed unexpectedly: <class 'httplib.BadStatusLine'>

これはおそらく、KumaScript サービスの一時的な障害です。ページの再読込みでこの問題が解決する事があります。これで問題が解決しない場合はスーパーリロード(shift + F5)を試してみて下さい。これらの試みの後もエラーが解消されない場合は、file an IT bug for Mozilla Developer Network to ask for an investigation.

古いテンプレートマクロ「wiki.languages() macros」によるエラーの解消

幾つかのページで、以下の様なスクリプトエラーメッセージを見かける場合があるでしょう。

Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but...

その様なページを編集状態にした場合、ページ下部に以下の様なマクロが見つかるかもしれません。

{{wiki.languages({ "zh-tw": "zh_tw/JavaScript/教學/JavaScript_概要", ... })}}

これは MDN の旧システム用のテンプレートの残存物であり、KUMA では不要です。上記テンプレートマクロを削除するか、あるいは旧システムの情報を残したい場合は以下の様に構文先頭 / 終端 の 「 {{ 」、「 }} 」を削除した上で、「 <!-- --> 」でコメントアウトするといいでしょう。

<!-- wiki.languages({ "zh-tw": "zh_tw/JavaScript/教學/JavaScript_概要", ... }) -->

Kuma は言語ページ間のリンクを自動的に生成します。いくつかコンバートに失敗しているページがありますが、将来的には解消されるでしょう。 バグ 782493

Unconverted inline script blocks

Occasionally, you'll find some text like this at the bottom of a page, or even somewhere in the middle:

autoPreviousNext("JSGChapters");
wiki.languages({
  "fr": "fr/Guide_JavaScript_1.5/Expressions_rationnelles",
  "ja": "ja/JavaScript/Guide/Regular_Expressions"
});

This is a script block that didn't get converted to a KumaScript macro during migration. It happens, unfortunately. If you switch to HTML source editing mode, you'll see this, a <pre class="script"> element:

<pre class="script" style="font-size: 16px;">
autoPreviousNext(&quot;JSGChapters&quot;);
wiki.languages({
  &quot;fr&quot;: &quot;fr/Guide_JavaScript_1.5/Expressions_rationnelles&quot;,
  &nbsp;&quot;ja&quot;: &quot;ja/JavaScript/Guide/Regular_Expressions&quot;
});
</pre>

This is an inline script - previously allowed by DekiScript, no longer supported by KumaScript.

For this particular example, common to the JavaScript Guide, you can fix it by removing the wiki.languages part (see previous section) and change the autoPreviousNext() into a macro like so:



If you see a block of code that's more complex than the above, you will need to create a new template, move the code there, and replace the code in its previous spot with a macro calling the new template.

ページの言語の取得

KumaScript では env.locale メソッドでマクロを埋め込んだページの言語を取得して簡単に利用する事が出来ます。

<%
  var lang = env.locale;

  if(lang === "ja") %>これは日本語のページです。<%
%>

旧システムの DekiScript テンプレートでは、言語の取得はやや難しいものでした。もし古いテンプレートが残っていれば、以下の様なコードを見かける事があるかもしれません。

/* accepts as input one required parameter: MathML element to create a xref to */
var u = uri.parts(Page.uri);
var lang = string.tolower(u.path[0]);

if (string.contains(lang, "project") || string.contains(lang, "Project")) {
  lang = string.substr(lang, 8);
}
/* ユーザページで使用可能にする為のフォールバック */
else if (string.StartsWith(lang, "user:")) {
  lang = page.language;
}

上記のようなコードを発見した場合、新しい KumaScript のコードに修正してください。 env.locale の値はすべてのページで定義されており、信頼性が高いものです。

ページの添付ファイルの内容を読み込む。

mdn.getFileContent() メソッドを用いる事により、添付ファイルの内容を取得する事が出来ます。

<%
  var contents = mdn.getFileContent(fileUrl);

  /* ... contents 変数を用いたコードをここに記述 ... */
%>

または、以下の様にして。

<%-mdn.getFileContent(fileObject)%>

ページの添付ファイル群は、env.files に配列として格納されています。よって、例えば、文書の添付ファイルの内の最初のものを埋め込むには、以下のようにします。

<%-mdn.getFileContent(env.files[0])%>
注記: You probably don't want to try to embed the contents of a non-text file this way, as the raw contents would be injected as text. This is meant to let you access the contents of text attachments.

If the file isn't found, an empty string is returned. There is currently no way to tell the difference between an empty file and a non-existent one. But if you're putting empty files on the wiki, you're doing it wrong.

テンプレートのローカライズ

基本は env.locale を取得し、この値を用いて分岐し、各言語での出力内容を変換する構造となります。しかしその分岐方法にはいくつかの方法があり、それぞれ向き不向きがあります。以下に各パターンを列挙します。

If/else ブロックを用いる例

もっとも簡単なものとして if/else を用いた分岐が挙げられます。

<% if ("fr" == env.locale) { %>
<%- template("CSSRef") %> « <a href="/fr/docs/Référence_CSS/Extensions_Mozilla">Référence CSS:Extensions Mozilla</a>
<% } else if ("ja" == env.locale) { %>
<%- template("CSSRef") %> « <a href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS リファレンス:Mozilla 拡張仕様</a>
<% } else if ("pl" == env.locale) { %>
<%- template("CSSRef") %> « <a href="/pl/docs/Dokumentacja_CSS/Rozszerzenia_Mozilli">Dokumentacja CSS:Rozszerzenia Mozilli</a>
<% } else if ("de" == env.locale) { %>
<%- template("CSSRef") %> « <a href="/de/docs/CSS_Referenz/Mozilla_CSS_Erweiterungen">CSS Referenz: Mozilla Erweiterungen</a>
<% } else { %>
<%- template("CSSRef") %> « <a href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a>
<% } %>

DekiScript ではこれを実現する為に <span lang="{locale}" という HTML 要素での分岐を用いていました。* は対応する言語ブロックが存在しなかった場合に表示されるワイルドカードとして機能していました。

<p><span lang="*" class="lang lang-*"><span class="script">CSSRef()</span> « <a href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a></span>
<span lang="en" class="lang lang-en"><span class="script">CSSRef()</span> « <a href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a>
<span lang="fr" class="lang lang-fr"><span class="script">CSSRef()</span> « <a href="/fr/Référence_CSS/Extensions_Mozilla">Référence CSS:Extensions Mozilla</a>
</span><span lang="ja" class="lang lang-ja"><span class="script">CSSRef()</span> « <a href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS リファレンス:Mozilla 拡張仕様</a></span>
<span lang="pl" class="lang lang-pl"> <span class="script">CSSRef()</span> « <a href="/pl/Dokumentacja_CSS/Rozszerzenia_Mozilli">Dokumentacja CSS:Rozszerzenia Mozilli</a></span>
<span lang="de" class="lang lang-de"><span class="script">CSSRef()</span> « <a href="/de/CSS_Referenz/Mozilla_CSS_Erweiterungen">CSS Referenz: Mozilla Erweiterungen</a></span></span></p>

この DekiScript の構文は既にサポートされていません。もしこのようなテンプレートを発見した場合は KumaScript のコードに書き換える必要があります。

Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there.

My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following:

%s#<span#^M<span#g
%s#<span lang="\(.*\)" .*>#<% } else if ("\1" == env.locale) { %>#g
%s#<span class="script">template.Cssxref(#<%- template("Cssxref", [#
%s#)</span> </span>#]) %>

Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all.

String variables and switch

Rather than switch between full chunks of markup is to define a set of strings, switch them based on locale, and then use them to fill in placeholders in a single chunk of markup:

<%
var s_title = 'Firefox for Developers';
switch (env.locale) {
    case 'de':
        s_title = "Firefox für Entwickler";
        break;
    case 'fr':
        s_title = "Firefox pour les développeurs";
        break;
    case 'es':
        s_title = "Firefox para desarrolladores";
        break;
};
%>
<span class="title"><%= s_title %></span>

You'll see examples of this in legacy DekiScript templates. For the most part, this pattern should work as-is, but you may need to adjust the expected values of locales. (eg. en, cn, pt become en-US, zh-CN, pt-PT respectively)

mdn.localString() の使用

Template:MDN:Common モジュールに新たに mdn.localString() が追加されています。これは以下の様に用います。

<%
var s_title = mdn.localString({
  "en-US": "Firefox for Developers",
  "de": "Firefox für Entwickler",
  "es": "Firefox para desarrolladores"
});

%><span class="title"><%= s_title %></span>

This is more concise than the switch statement, and may be a better choice where a single string is concerned. However, if many strings need to be translated (eg. as in CSSRef), a switch statement might help keep all the strings grouped by locale and more easily translated that way.

これは switch 文による分岐よりも簡潔であり、テンプレート内で一種類や二種類程度の文字列のみの翻訳が必要なケースなどでは、switch 文より良い選択となるかもしれません。ロケールにより多くの文字列を切り替える必要がある場合(※例: Template:CSSRef | MDN)は、switch 文 を用いた方が良いでしょう。 if 文を用いた場合が良い場合もあります。適切なものを選択して御利用下さい。

例: ビフォー & アフター

Carriage returns added here and there for clarity.

// Before: DOM0() template Dekiscript
<p><span class="lang lang-en" lang="en">DOM Level 0. Not part of any standard. </span>
<span class="lang lang-es" lang="es">DOM Nivel 0. No es parte de ninguna norma. </span>
<span class="lang lang-*" lang="*">DOM Level 0. Not part of any standard. </span>
<span class="lang lang-fr" lang="fr">DOM Level 0. Ne fait partie d'aucune spécification. </span>
<span class="lang lang-ja" lang="ja">DOM Level 0。どの標準にも属しません。 </span>
<span class="lang lang-pl" lang="pl">DOM Level 0. Nie jest częścią żadnego standardu. </span>
<span class="lang lang-zh-cn" lang="zh-cn">DOM Level 0 不属于任何标准.</span></p>

// After: Kumascript version
<% if ("fr" == env.locale) { %>
<p>DOM Level 0. Ne fait partie d'aucune spécification.</p>
<% } else if ("ja" == env.locale) { %>
<p>DOM Level 0。どの標準にも属しません。 </p>
<% } else if ("pl" == env.locale) { %>
<p>DOM Level 0. Nie jest częścią żadnego standardu.</p>

<% } else if ("es" == env.locale) { %>
<p>DOM Nivel 0. No es parte de ninguna norma.</p>
<% } else if ("zh-CN" == env.locale) { %>
<p>DOM Level 0 不属于任何标准.</p>
<% } else { %>
<p>DOM Level 0. Not part of any standard.</p>
<% } %>
// From ReleaseChannelInfo() template
// Before:
web.html("<p>Firefox " + $0 + ", based on Gecko " + $1 + ", will ship in " + $2 + ".
 This article provides information about the changes in this release that will 
 affect developers. Nightly builds of what will become Firefox " + $0 + " are "
  + web.link(url, "currently available") + " on the " + string.ToUpperFirst($3)
  + " channel.</p>");

// After:
<p>Firefox <%= $0 %>, based on Gecko <%= $1 %>, will ship in <%= $2 %>. This
 article provides information about the changes in this release that will 
 affect developers. Nightly builds of what will become Firefox <%= $0 %> 
 are <%- web.link(url, "currently available")%>  on the
 <%= string.ToUpperFirst($3) %> channel.</p>
// Before: old Dekiscript snippet
if ($1 && string.length($1)) {
  optionsText = optionsText + "<li>" + LXRSearch("ident", "i", $1) + "</li>";
}

// After: new Kumascript. Quote parameters to template() unless it is an arg variable (like $1).
if ($1 && string.length($1)) {
    optionsText = optionsText + "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>";
}

// Note that template() within <% ... %> outputs nothing directly. If you want to call another
// template and display its output, use <%= %> or <%- %> like this:
<%- template("LXRSearch", ["ident", "i", $1]) %>

関連情報

ドキュメントのタグと貢献者

タグ: 
 このページの貢献者: hamasaki, ethertank
 最終更新者: hamasaki,