How to add a variable to a view template in Backbone
You have a view who has a Collection and you want to add an additional variable to use in your template,.
Let say you want to add the variable sapConfig and do some dynamic rendering based on that value.
<option value="all">All</option>
<option value="configured" <% if (sapConfig == "configured") { %> selected="selected" <% } %>>Configured</option>
<option value="sapOnly" <% if (sapConfig == "sapOnly") { %> selected="selected" <% } %>>SAP Only</option>
In my case the view was using a collection only and generating child views. So the view itself had no model. I could have created a new model just for this view-specific param, but it is overkill for just some rendering dynamics with no data exchange with the server. What you can do is add a parameter to a serialize() function :
Streams.Views.Layout = Backbone.View.extend({
template: "streamsLayout",
sapConfig: "configured",
serialize: function() {
return {
sapConfig: this.sapConfig
};
},
(...)
});
Note : If you use Marionnette library, the serialize function is named serializeData: function() {};
Recent Comments