Rahul Chandra
Rahul Chandra

Reputation: 583

Backbone.Marionette - Accessing variables in the ItemView template or CompositeView template

Here i want to access a variable or a list of variables which is passed when initalizing a new view from its corresponding template.

Code example

Creating a list view

@Taskit.module "Tasks.List", (List, Taskit, Backbone, Marionette, $, _) ->
    class List.NewTask extends Taskit.Views.ItemView
        template: JST["backbone/taskit/tasks/tasks/list/_templates/new_task"]

Template for the above list view

<div id="new-task-form">
</div>

Initializing the ItemView

view = new Taskit.Tasks.List.NewTask
    project_id: "project_id"

Here my question is how can i access the "project_id" variable from its template.

<%= project_id %> #is not working

In Backbone it can be achieved by

$(@el).html(@template({task: @model, project_id: "project_id"}))

how to do it in Marionette.js?

Upvotes: 6

Views: 6337

Answers (1)

Scott Puleo
Scott Puleo

Reputation: 3684

You can provide your own method to serialize data:

https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.itemview.md#itemview-serializedata

Backbone.Marionette.ItemView.extend({
  serializeData: function(){
    var data = this.model.toJSON();
    data.project_id = this.project_id;

    return data;
  }
});

Upvotes: 12

Related Questions