Search code examples
jsonbackbone.jstumblrmarionette

Tumblr API / Dashes in property names


I'm using Backbone and Marionette to display a list of tumblr-posts. I want to use the thumbnail available in the JSON api, but this presents me with a problem. The url I want to fetch is called "photo-url-100": "http://blablablablabla". Normally in JS I would use parentObject['photo-url-100'], but as I'm iterating through all items with Backbone / Marionette, there is no root node available as far as I'm aware (all properties are directly available, so for example <%= id %> instead of <%= post.id %>. Can someone point me in the right direction as to how I should handle this?

Some clarification: I'm using MarionetteJS. As per Tumblr's doc I've added their "API" (in my case http://gentletruths.tumblr.com/api/read/json) as a script-tag in my header, effectively "bootstrapping" it. I process it as a collection, and each post as a model. This collection is then handled by a Backbone.Marionette.CompositeView, and each model by a Backbone.Marionette.ItemView. So in my ItemView template (below) the id works (as a reference), but the photo-url-100 doesn't.

<script id="instagram_item_template" type="text/template">
    <a href="#" class="photos__frame">
        <span class="caption"><%= id %></span>
        <img src="<%= photo-url-100 %>" alt="" class="photos__photo">
    </a>
</script>

I've consulted Marionette's annotated source (render function here: http://marionettejs.com/docs/backbone.marionette.html#section-188), but I'm not sure how to properly read this and deduce how the data is made available.


Solution

  • When rendering a _.template(), simply wrap your parentObject inside another object:

    var compiled = _.template("<img id=\"<%= post.id %>\" src=\"<%= post['photo-url-100'] %>\">");
    compiled({ 'post': parentObject });
    

    Edit:

    Your template:

    <script id="instagram_item_template" type="text/template">
      <a href="#" class="photos__frame">
        <span class="caption"><%= post.id %></span>
        <img src="<%= post['photo-url-100'] %>" alt="" class="photos__photo">
      </a>
    </script>
    

    Rendering template:

    Backbone.Marionette.ItemView.extend({
      tagName: "li",
      template: function(data){
        return _.template($('#instagram_item_template').html(), { 'post': data })
      }
    });