Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate inside html attributes with Underscore.js

I'm building an application using Backbone.js, Underscore.js, HAML, and Coffeescript.

The problem I'm having is getting variables to interpolate inside of html element attributes.

<% _.each(collection.models, function(document) { %>
%tr
  %td
    %input{:type => 'checkbox', :name => "documents[]", :value => "<%= document.attributes.id %>"}
  %td <%= document.attributes.id %>
  %td <%= document.attributes.name %>

  <% } %>
<% }); %>

The object's values are displaying properly inside of the <td>, but not within the input's value attribute.

Is interpolation inside of an element's attributes possible? I was not able to find a solution.

Thanks

like image 511
Chris Avatar asked Nov 30 '11 20:11

Chris


2 Answers

The solution to this problem is to use HAML's :escape_attrs option.

Haml::Engine.new(template, :escape_attrs => false).render
like image 61
Chris Avatar answered Nov 04 '22 09:11

Chris


You can try using html_safe which is a method on String objects. This will escape the html characters in the variable statement (< for example) and will leave the intact for underscore to evaluate at runtime:

%input{:type => 'checkbox', :name => "documents[]", :value => "<%= document.attributes.id %>".html_safe}

(Tested on rails 3.0.13)

like image 36
Erez Rabih Avatar answered Nov 04 '22 09:11

Erez Rabih