Question

I'm working on a backbone application right now and I've a problem with sessionStorage values I think. If you think there's something else that's wrong just tell me!

When I run this script:

    <script>
      console.log((sessionStorage.appRole == "1" || sessionStorage.appRole == "2"));
    </script>

Then the outcome in the console is true.

But when the value is used to the template in my backbone using underscorejs the value inside of the IF statement aint rendered. But when I refresh my page then the button is visible. I wonder why it doesn't work the first time I visit the page. The value is correct but it's not being rendered.

    <% if (sessionStorage.appRole == "1" || sessionStorage.appRole == "2") { %>
      <button id="create" class="btn btn-primary"><%= i18n.create_user %></button>
    <% } %>

Do you have any ideas? I've scratched my head for hours and now I beg for your help!

Was it helpful?

Solution

You should fetch the values and store it to a variable and then pass it to the template. Since template is seeking for a value to be in that variable it is failing.

var appRole = sessionStorage.appRole;
var user = i18n.create_user;

Pass the appRole,user values to the template

$(this.el).html(this.myTemplate({"appRole": appRole,"userDetail":user }));

Inside template fetch it like

<% if (appRole == "1" || appRole == "2") { %>
<button id="create" class="btn btn-primary"><%= userDetail %></button>
<% } %>

For myTemplate ,Include your template in view and assign it using the underscore template function.

myTemplate : _template(sampleTemplate),

And use the this.myTemplate(mymodelobj.toJSON()); where ever you need.

Look at the sample view file

define([
     'jquery',
     'underscore',
     'backbone',
     // Using the Require.js text! plugin, we are loaded raw text
     // which will be used as our views primary template
     'text!templates/project/list.html'
   ], function($, _, Backbone, projectListTemplate){
  var ProjectListView = Backbone.View.extend({
      el: $('#container'),
      render: function(){
              // Using Underscore we can compile our template with data
      var data = {};//json data
      var compiledTemplate = _.template( projectListTemplate, data );
      // Append our compiled template to this Views "el"
      this.$el.append( compiledTemplate );
   }
});

// Our module now returns our view return ProjectListView; });

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top