1
1

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.

underscore.templateでJSのソースを生成する際にテンプレートにvalidなJSを使う

Posted at

Underscore.jsのtemplate methodはERBライクな記法の極めてシンプルなテンプレートエンジンですが、正規表現を指定することで記法をカスタマイズすることが出来ます。
今回はJSのソースを生成するために使うので、以下のようにしてみました。

templateSettings.js
_.templateSettings.interpolate=/0?\/\*\s*%=([\s\S]+?)%\s*\*\//g;
_.templateSettings.evaluate=/0?\/\*\s*%([\s\S]+?)%\s*\*\//g;

どういう記法なのかというと、JSのブロックコメントorJSのブロックコメントの手前に0が付いている物の中に、
%=と%でくくられた範囲があればcontextの変数を展開し、%と%ででくくられた範囲があれば範囲内のJSをテンプレート処理時に実行するというものです。

使用例はこちら

template.js
  var configs = [
/*%
configs.forEach(function(config){
var isNotLast = configs.indexOf(config) !== (configs.length - 1)
%*/
/* %=config% */
0/*% if(isNotLast){ %*/,0/*% }
}) %*/
  ];

テンプレート記法がブロックコメントなのでJSのソースが壊れませんし、コメント以外に0も入れられるのでテンプレート外にカンマを入れていても[,]のようになるのも防げます。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?