开发者

How to send back js.haml in rails

I have a rails create action which send back some jquery in a file:

create.js.erb

开发者_高级运维var appearance = $("<%= escape_javascript(render(:partial => @appearance)) %>").effect("highlight", {color: '#E6ff00'}, 2000);
$("#sortable").append(appearance);
$("#new_appearance")[0].reset();

I have started using HAML and want to know how I should be converting this. Can I use js.haml? If so what should the markup look like?


Actually, returning JS in HAML is pretty easy, just use the :plain filter and enclose anything you want evaluated in #{}.

:plain
  var appearance = $("#{escape_javascript(render(:partial => @appearance)}").effect("highlight", {color: '#E6ff00'}, 2000);
  $("#sortable").append(appearance);
  $("#new_appearance")[0].reset();

Do not use the :javascript filter as it will enclose everything in a tag which is unnecessary.

If you need to use some logic, just put the :plain inside the nesting.

- if params[:printing]
  :plain
    $('#print-view').html("#{escape_javascript(render 'print_preview')}");

Sorry ERB.


Haml's really meant to generate HTML. You could, in theory, use create.js.haml, but ERB makes much more sense when you're writing Javascript.


Well looks like you dont need the != in front of each line. The following works for me just fine. Im using Rails 3 and latest version of HAML

$('#comments_table_header').after('#{escape_javascript(render :partial => 'row', :locals => { :comment => @comment })}');


In a js.haml it would look something like

!= "var appearance = $('<%= escape_javascript(render(:partial => @appearance)) %>').effect('highlight', {color: '#E6ff00'}, 2000);"
!= "$('#sortable').append(appearance);"
!= "$('#new_appearance')[0].reset();"

Note the HAML != syntax which prevents the generated text from being HTML escaped. I do agree that ERB is a better fit here, but for consistency stake you might still want to go the HAML way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜