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

1

6

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?

Sapiential answered 5/5, 2013 at 21:14 Comment(0)
M
12

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;
  }
});
Masonry answered 5/5, 2013 at 23:57 Comment(3)
There is templateHelpers attribute in Marionette views which can be used to pass data to its template. To pass data to ItemView u can use itemViewOptions attribute of collection/composite viewDodwell
+1 for templateHelpers. Docs: marionettejs.com/docs/marionette.view.html#viewtemplatehelpersGomer
Marionette core here, you should be using templateHelpers if you want additional data in your view. Use serializeData if you need to transform the data in a model or collection.Doorjamb

© 2022 - 2024 — McMap. All rights reserved.