Backbone view, needs to render an image in the template depending on params

1k Views Asked by At

So I have a view that is going to render a template that will include an image. This image is dependent on the variable being passed in, located in assets/images.

Basically, how can I pass in this model into the template so it can render the correct image?

Normally in Rails I would just do in a Rails ERB Template:

<img class="item-portrait" 
src="<%= image_path("items/" + item.name.gsub(" ", "-").downcase + ".png")
 %>">

How can I accomplish the same effect in a JST template?

1

There are 1 best solutions below

2
ne8il On

Let's assume your model looks like this :

var itemPortraitModel = new Backbone.Model({
  'path' : 'path_to_file'
});

and your view is similar to this :

var ItemPortraitView = Backbone.View.extend({
  template: JST['itemPortraitTemplate'],
  render: function() {
    this.$el.html(this.template(this.model.attributes));
    return this;
  }
});

then in your itemPortraitTemplate template code, any of the properties in your model will be available:

<img class="item-portrait" 
src="<% print(("items/" + path + ".png") %>">