0

Right now I'm using the following line of code to retrieve an Underscore template and create a DOM element from the template, using jQuery.

var element = $(_.template($('#template').html())());

It works, but I think this looks a bit messy/confusing, so I was wondering if there's a better way to do this?

4

1 に答える 1

4

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'));

それをどのように機能に分解するかは、他の場所で使用するパーツの好みによって異なります。

于 2012-10-24T20:17:25.347 に答える