最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Interpolate inside html attributes with Underscore.js - Stack Overflow

programmeradmin0浏览0评论

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

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

Share edited Jan 8, 2012 at 22:34 Charles 51.5k13 gold badges106 silver badges144 bronze badges asked Nov 30, 2011 at 20:17 ChrisChris 1459 bronze badges 3
  • I'm not experienced in this area, but please have a look here if this is what you need. It supports coffeescript in attributes. – kubetz Commented Nov 30, 2011 at 20:53
  • I'm not sure what's wrong with your code, but I have used interpolation with underscore templates. – Jack Commented Dec 1, 2011 at 3:40
  • The problem is with interpolation inside of html element attributes. – Chris Commented Dec 1, 2011 at 13:17
Add a ment  | 

3 Answers 3

Reset to default 4

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

Haml::Engine.new(template, :escape_attrs => false).render

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)

It looks like you aren't closing the function in the template properly ( try adding <% }); %> to the end of your template).

I'm not really familiar with HAML syntax but here's a simple example on jsfiddle using plain HTML and an underscore template. As you can see you can definitely use interpolation in middle of an elements attributes.

发布评论

评论列表(0)

  1. 暂无评论