Search code examples
backbone.jsunderscore.jsbackbone-viewsunderscore.js-templating

It possible to show attributes from model to other attributes from model?


Hi i have a view with model attributes :

name: "P",
surname: "a",
sorters: ["name","surname"]   // dynamical array ( parameter to show )

in template :

<% for(i=0 ;i<sorters.length(); i++ ){ %>
   <h2><%= sorters[0] %></h2>   // its <%= 'name' %> with quotes 
<% } %>

as result i got

name, surname

i need get

P, a

As result i get values from Sorters[array] not model values:

Some examples

1.

name: "P",
surname: "a",
sorters: ["name"] 

P

2.

name: "P",
surname: "a",
sorters: ["surname","name"] 

a, P

With this code in template i dont have a values from models but string text from my array and my view instead of attributes from model show labels


Solution

  • Based on the fact that sorters returns a value which appears to be equal to another field in the model, you wish to dynamically return that field.

    There's a few ways to do this, probably the best is to provide the variable option when creating the template (docs). See example below:

    var model = new Backbone.Model({
      name: "P",
      surname: "a",
      sorters: ["name","surname"]
    });
    
    var tmp = _.template($('#template').html(), {variable: 'data'});
    $('#result').html(tmp(model.attributes));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
    <script id="template" type="text/template">
    <% for(i=0; i < data.sorters.length; i++ ){ %>
       <h2><%= data[data.sorters[i]] %></h2>
    <% } %>
    </script>
    <div id="result"/>

    Also, better to use each rather than a for loop:

    <% _.each(data.sorters, function(sorter) { %>
       <h2><%= data[sorter] %></h2>
    <% }) %>