16

テンプレートは次のようになります。

<div>
    <H5>Status for your request</H5>
    <table>
    <tbody>
    <tr>
        <th>RequestId</th>
        <th><%=id%></th>
    </tr>
    <tr>
        <th>Email</th>
        <th><%=emailId%></th>
    </tr>       
    <tr>
        <th>Status</th>
        <th><%=status%></th>
    </tr>       
     </tbody>
     </table>
</div>

これは、ページをレンダリングするViewJavascriptです。

window.StatusView = Backbone.View.extend({

initialize:function () {
    console.log('Initializing Status View');
    this.template = _.template(tpl.get('status'));
},

render:function (eventName) {

    $(this.el).html(this.template());
    return this;
},

events: { "click button#status-form-submit" : "getStatus" },

getStatus:function(){

    var requestId = $('input[name=requestId]').val();
    requestId= $.trim( requestId );

    var request  = requests.get( requestId );

    var statusTemplate = _.template(tpl.get('status-display'));
    var statusHtml = statusTemplate( request );
    $('#results-span').html( statusHtml );
}

});

入力をクリックすると、requestIdが読み取られ、ステータスがhtml要素にID'results-span'で追加されます。

html-templateの値を変数値に置き換えると、失敗が発生します。

var statusTemplate = _.template(tpl.get('status-display'));
var statusHtml = statusTemplate( request );

レンダリングは次のエラーで失敗します。

Uncaught ReferenceError: emailId is not defined
(anonymous function)
_.templateunderscore-1.3.1.js:931
window.StatusView.Backbone.View.extend.getStatusstatus.js:34
jQuery.event.dispatchjquery.js:3242
jQuery.event.add.elemData.handle.eventHandle
4

2 に答える 2

23

アンダースコア_.template

JavaScriptテンプレートを、レンダリング用に評価できる関数にコンパイルします。
[...]

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

したがって、基本的には、テンプレート関数にオブジェクトを渡し、テンプレートはそのオブジェクト内でテンプレートで使用する値を探します。あなたがこれを持っているなら:

<%= property %>

テンプレートで、テンプレート関数をとして呼び出すと、t(data)テンプレート関数はを検索しdata.propertyます。

通常、ビューのモデルをJSONに変換し、そのオブジェクトをテンプレートに渡します。

render: function (eventName) {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
}

私はあなたが何でeventNameあるか、またはあなたがそれで何をすることを計画しているのかわかりませんが、あなたはこの構造を持つオブジェクトを取得する必要があります:

data = { id: '...', emailId: '...', status: '...' }

どこかからそれをテンプレート関数に渡します。

var html = this.template(data)

ページに配置するHTMLを取得します。

デモ(説明のための偽のモデルを使用):http://jsfiddle.net/ambiguous/hpSpf/

于 2012-05-01T21:04:06.147 に答える
3
OptionalExtrasView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    render: function() {
        // Get the product id
        //var productid = $( this ).attr( "productid" );
        var data = {name : 'moe'};

        var tmpl = _.template($('#pddorder_optionalextras').html() );
        this.$el.html(tmpl(data));
    }
});

   var search_view = new OptionalExtrasView({ el :     $('.pddorder_optionalextras_div')});

ボディタグの直前:

      <script type="text/template" id="pddorder_optionalextras">
   <%= name %>
    </script> 
于 2015-02-08T04:36:01.803 に答える