Underscore 1.7+ 用に更新_.template
:常に関数を返すため、新しいバージョンの Underscore でできることはあまりありません。
template _.template(templateString, [settings])
JavaScript テンプレートをレンダリング用に評価できる関数にコンパイルします。
_.template(tmpl, data)
以前は、入力済みのテンプレートを取得するために (以下を参照)と言うことができましたが、現在はできません。
ただし、関数内の括弧の一部を次のように非表示にすることができます。
var tmpl_to_html = function(id) {
var $el = $('#' + id);
var fn = _.template($el.html());
return fn();
};
var $e = $(tmpl_to_html('template'));
また:
var tmpl_to_html = function(id, data) {
var $el = $('#' + id);
var fn = _.template($el.html());
return fn(data);
};
var $e = $(tmpl_to_html('template'));
var $x = $(tmpl_to_html('other', { a: 'b' }));
Underscore の古いバージョンの場合:パラメータを指定_.template
することで、入力済みのテンプレートを取得できます。data
template _.template(templateString, [data], [settings])
[...] 1 回限りのものを作成している場合は、テンプレート関数を返す代わりにすぐにレンダリングするために、データオブジェクトをtemplate
の 2 番目のパラメーターとして
渡すことができます。
おそらく真実のすべてが当然のことですdata
が、空のオブジェクトがおそらくあなたの最善の策です:
var $e = $(_.template($('#template').html(), { }));
それはまだ少しうるさいですが、いつでも_.template
別の関数で呼び出しをラップできます:
var tmpl_to_html = function(id) {
var $el = $('#' + id);
return _.template($el.html(), { });
};
var $e = $(tmpl_to_html('template'));
それをどのように機能に分解するかは、他の場所で使用するパーツの好みによって異なります。