Japanese translation from the original post in English.
原文: [Getting Literal With ES6 Template Strings by Addy Osmani] (http://updates.html5rocks.com/2015/01/ES6-Template-Strings)
<
US> #Getting Literal With ES6 Template Strings
#ES6のテンプレート文字列
<
US> Strings in JavaScript have been historically limited, lacking the capabilities one might expect coming from languages like Python or Ruby. ES6 Template Strings (available in Chrome 41+), fundamentally change that. They introduce a way to define strings with domain-specific languages (DSLs), bringing better:
従来のJavaScriptの文字列処理はPythonやRubyに比べて非力でしたが、ES6のテンプレート文字列はこの状況を根本的に覆します。(テンプレート文字列はChrome 41からサポートされています。)それによりプログラマはドメイン固有言語(domain-specific language、DSL)を定義する事が可能になります。以下はテンプレート文字列が提供する機能です。
<
US> * String interpolation <US> * Embedded expressions <US> * Multiline strings without hacks <US> * String formatting <US> * String tagging for safe HTML escaping, localisation and more.
- 文字列の挿入
- 式を文字列に埋め込む
- 複数行に渡る文字列を簡単に記述できる
- 文字列の整形
- 文字列へのタグ付けによるHTMLエスケープ、ローカライズ
<
US> Rather than stuffing yet another feature into Strings as we know them today, Template Strings introduce a completely different way of solving these problems.
上記の機能を実現するために、テンプレート文字列の仕様では、既存のJavaScriptの文字列に機能を追加するのではなく、まったく異なるシンタックスが導入されました。
<
US> ## Syntax
##シンタックス
<
US> Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
テンプレート文字列では従来JavaScriptの文字列で使われていたシングルクォートもしくはダブルクォートではなく、バッククォート(`)が使用されます。以下のような記述となります。
var greeting = `Yo World!`;
<
US> So far, Template Strings haven't given us anything more than normal strings do. Let’s change that.
このままでは従来の文字列と機能的に何ら変わらないので、以降で変更を加えていきます。
<
US> ## String Substitution
##文字列置換
<
US> One of their first real benefits is string substitution. Substitution allows us to take any valid JavaScript expression (including say, the addition of variables) and inside a Template Literal, the result will be output as part of the same string.
まず、テンプレート文字列の一番分かりやすい使い方は文字列置換です。文字列置換はテンプレート文字列の中にJavaScriptの式(例:複数の変数を文字列演算子で連結したもの等)を配置することで行います。
<
US> Template Strings can contain placeholders for string substitution using the${ }syntax, as demonstrated below:
以下のようにテンプレート文字列中の${ }で囲われた部分はプレースホルダーとして作用するので、ここに式を記述します。
// <~US~> Simple string substitution
// 文字列置換
var name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
<
US> As all string substitutions in Template Strings are JavaScript expressions, we can substitute a lot more than variable names. For example, below we can use expression interpolation to embed for some readable inline math:
文字列置換のプレースホルダー内では通常のJavaScriptの式が使用できるため、変数名以外にも様々なものを記述することができます。例えば以下のように短い数式をインラインで埋め込むことも可能です。
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
console.log(`The number of JS MVC frameworks is ${2 * (a + b)} and not ${10 * (a + b)}.`);
//=> The number of JS frameworks is 40 and not 2000.
<
US> They are also very useful for functions inside expressions:
また、以下のように関数呼び出しも行えます。
function fn() { return "I am a result. Rarr"; }
console.log(`foo ${fn()} bar`);
//=> foo I am a result. Rarr bar.
<
US> The${}works fine with any kind of expression, including member expressions and method calls:
その他にも${}の中にはプロパティのアクセスやメソッド呼び出し等、あらゆるタイプの式が記述できます。
var user = {name: 'Caitlin Potter'};
console.log(`Thanks for getting this into V8, ${user.name.toUpperCase()}.`);
// => "Thanks for getting this into V8, CAITLIN POTTER";
// その他の例
var thing = 'drugs';
console.log(`Say no to ${thing}. Although if you're talking to ${thing} you may already be on ${thing}.`);
// => Say no to drugs. Although if you're talking to drugs you may already be on drugs.
<
US> If you require backticks inside of your string, it can be escaped using the backslash character\as follows:
テンプレート文字列の中でバッククォートの文字を使いたい場合は、以下のようにバックスラッシュ(\)を使ってエスケープします。
var greeting = `\`Yo\` World!`;
<
US> ## Multiline Strings
##複数行に渡る文字列
<
US> Multiline strings in JavaScript have required hacky workarounds for some time. Current solutions for them require that strings either exist on a single line or be split into multiline strings using a\(blackslash) before each newline. For example:
従来、JavaScriptで複数行の文字列を扱おうとするとトリッキーにならざるを得ませんでした。文字列が複数行に渡る場合、改行の前にバックスラッシュ(\)を挿入する必要があります。
var greeting = "Yo \
World";
<
US> Whilst this should work fine in most modern JavaScript engines, the behaviour itself is still a bit of a hack. One can also use string concatenation to fake multiline support, but this equally leaves something to be desired:
上記のやり方はほとんどのJavaScriptエンジンで動作しますが、若干ハックのようにも感じられます。また、以下のように文字列演算子で複数行を連結するやり方もありますが、これもベストなやり方とは言いがたいです。
var greeting = "Yo " +
"World";
<
US> Template Strings significantly simplify multiline strings. Simply include newlines where they are needed and BOOM. Here's an example:
そこで、テンプレート文字列を使えば複数行に渡る文字列を簡単に扱うことができます。これは何も特別なことをする必要はなく、以下のように単純に改行するだけです。
console.log(`string text line 1
string text line 2`);
<
US> Any whitespace inside of the backtick syntax will also be considered part of the string.
ちなみに、バッククォート内の空白は通常の文字列と同じように扱われます。
<
US> ## Tagged Templates
##タグ付けされたテンプレート文字列
<
US> So far, we've looked at using Template Strings for string substitution and for creating multiline strings. Another powerful feature they bring is tagged templates. Tagged Templates transform a Template String by placing a function name before the template string. For example:
ここまででテンプレート文字列を使って文字列置換と複数行に渡る文字列を扱う方法について見てきましたが、その他の強力な機能として、テンプレートのタグ付け機能があります。タグ付けされたテンプレート文字列を記述するには、テンプレートの前に関数名を配置します。以下に例を示します。
fn`Hello ${you}! You're looking ${adjective} today!`
<
US> The semantics of a tagged template string are very different from those of a normal one. In essence, they are a special type of function call: the above "desugars" into
上記のタグ付けされたテンプレートは、通常のテンプレート文字列の構文とは異なり、関数呼び出しへと解釈されます。上記のテンプレート文字列の構文糖衣を取り除くと以下のようになります。
fn(["Hello ", "! You're looking ", " today!"], you, adjective);
<
US> Note: Nicholas Zakas goes into more detail on the break-down of these arguments in the Template Strings section of his excellent book, Understanding ES6.
注:Nicholas Zakasの『Understanding ES6』では、これらの引数の分解の仕組みについて、さらに詳しく説明されています。
<
US> Note how the (n + 1)th argument corresponds to the substitution that takes place between the nth and (n + 1)th entries in the string array. This can be useful for all sorts of things, but one of the most straightforward is automatic escaping of any interpolated variables.
上記の関数呼び出しで、第一引数の配列にテンプレート文字列のリテラルが格納されています。そして第二引数以降の引数はリテラルとリテラルの間に挿入されます。つまり、(n + 1)番目の引数は配列中のn番目と(n + 1)番目の要素のリテラルの間に挿入されます。この機能は様々な用途が考えられますが、最も単純なものは挿入された変数の文字列をエスケープするというものです。
<
US> For example, you could write a HTML-escaping function such that..
例えばHTMLの文字列を自動的にエスケープするテンプレート文字列は以下のようになります。
html`<p title="${title}">Hello ${you}!</p>`
<
US> returns a string with the appropriate variables substituted in, but with all HTML-unsafe characters replaced. Let’s do that. Our HTML-escaping function will take two arguments: a username and a comment. Both may contain HTML unsafe characters (namely ', ", <, >, and &). For example, if the username is "Domenic Denicola" and the comment is "& is a fun tag", we should output:
このテンプレート文字列では変数の値がそのまま展開されるのではなく、HTMLでそのまま使用できない文字をエスケープ処理した上で挿入されます。では実際にそのようなコードを書いてみましょう。ここで、ユーザ名とコメントを引数として受け取るテンプレートを想定してください。両方の引数とも、HTMLでそのまま使用できない文字、すなわち(')、(")、(<)、(>)、そして(&)を含む可能性があります。例えば、"Domenic Denicola"というユーザ名と、"& is a fun tag"というコメントが入力された場合、以下のような出力となります。
<b>Domenic Denicola says:</b> "& is a fun tag"
<
US> Our tagged template solution could thus be written as follows:
この場合、タグ付けされたテンプレート文字列は以下のように記述されます。
function html(pieces) {
var result = pieces[0];
var substitutions = [].slice.call(arguments, 1);
for (var i = 0; i < substitutions.length; ++i) {
result += escape(substitutions[i]) + pieces[i + 1];
}
return result;
}
function escape(s) {
return s.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/'/g, "'")
.replace(/"/g, """);
}
var username = "Domenic Denicola";
var tag = "& is a fun tag";
console.log(html`<b>${username} says</b>: "${tag}"`);
//=> <b>Domenic Denicola says</b>: "& is a fun tag"
<
US> Other possible uses include auto-escaping, formatting, localisation and in general, more complex substitutions:
エスケープ以外にも、文字列整形、ローカライズ等、その他あらゆる複雑な文字列処理をタグ付けの機能を使って行う事ができます。
// <~US~> Contextual auto-escaping
// より高機能なエスケープ処理
qsa`.${className}`;
safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}">${message}</a>`;
// <~US~> Localization and formatting
// ローカライズと文字列整形
l10n`Hello ${name}; you are visitor number ${visitor}:n! You have ${money}:c in your account!`
// <~US~> Embedded HTML/XML
// HTML/XMLの埋め込み
jsx`<a href="${url}">${text}</a>` // <~US~> becomes React.DOM.a({ href: url }, text)
jsx`<a href="${url}">${text}</a>` // React.DOM.a({ href: url }, text)に変換される
// <~US~> DSLs for code execution
// コマンド実行するためのDSL
var childProcess = sh`ps ax | grep ${pid}`;
<
US> ## Summary
##まとめ
<
US> Template Strings are in Chrome 41 beta+, IE Tech Preview, Firefox 35+ and io.js. Practically speaking if you would like to use them in production today, they're supported in major ES6 Transpilers, including Tracuer and 6to5. Check out our Template Strings sample over on the Chrome samples repo if you'd like to try them out. You may also be interested in ES6 Equivalents in ES5, which demonstrates how to achieve some of the sugaring Template Strings bring using ES5 today.
テンプレート文字列はChromeベータ版のバージョン41以上、IEの開発者プレビュー版、Firefoxバージョン35以上、そしてio.jsで使用可能です。その他にもTracuerや6to5のようなメジャーなES6トランスパイラを使えば今すぐにでもプロダクションの環境で使用することが可能です。Chrome のサンプルリポジトリに テンプレート文字列のサンプルがありますので、実際に試すときにお使いください。また、ES6とES5のコード比較を見ることで、テンプレート文字列と同等の機能をES5で実現するにはどうすればよいか理解できると思います。
<
US> Template Strings bring many important capabilities to JavaScript. These include better ways to do string & expression interpolation, multiline strings and the ability to create your own DSLs.
テンプレート文字列はJavaScriptにたくさんの重要な機能をもたらします。それにより、文字列や式の挿入が可能になり、複数行に渡る文字列を扱うことが容易になり、また、独自のDSLを定義することができるようになります。
<
US> One of the most significant features they bring are tagged templates - a critical feature for authoring such DSLs. They receive the parts of a Template String as arguments and you can then decide how to use the strings and substitutions to determine the final output of your string.
最も重要な機能はテンプレートのタグ付けの機能であり、それによりDSLを作成することができます。テンプレート文字列の一部を引数として受け取り、それらに対して任意の処理を行った後に置換することで、最終的な出力を自身で決定する事ができます。
<
US> ## Further Reading
##参考文献