3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jsで未定義の変数を含むテンプレート文字列を定義する

Posted at

ES6には、テンプレート文字列(Template literal)という便利な構文があります。

Template literal は組み込み式を扱うことができる文字列リテラルです。

テンプレート文字列 - JavaScript | MDNより)

テンプレート文字列は${}を用いて文字列中に変数(というか式)を挿入することができます。

const a = 456;
const b = `123${a}789`;

console.log(b); // -> 123456789

当たり前なのですが、上の場合、aが前もって定義されてない場合、エラーを起こします。
でも「テンプレート」ってそうじゃないじゃん。
後から定義できてこそのテンプレートじゃん。

....という人たちのための書き方があります。
手っ取り書くと以下になります。

// 未定義テンプレート文字列関数
const tmpl = raws => (...subs) => String.raw(raws, ...subs);

// テンプレートを定義
const gt = tmpl`12${0}56${0}`;

console.log(gt());       // -> 1256
console.log(gt(34));     // -> 123456
console.log(gt(34, 78)); // -> 12345678

最初にタグ関数を処理するための関数(tmpl)を定義しておき、これを使ってテンプレート(gt)を作ります。
あとは関数として呼び出して引数に入れたいものを入れるだけです。
引数を指定せず呼んだ場合は、その部分は無視されます。

これを使えば、

const gt = tmpl`
  <dl>
    <dt>${0}</dt>
    <dd>${0}円</dd>
  </dl>
`;

みたいなHTMLのテンプレートを前もって定義しておいて、後から変数を指定して使いまわしたり、ということができるようになります。
ただ、変数部分がいっぱいある時は、それを順番に入れていかなくてはならないのが不便ですが....。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?