Coda Chang Coda Chang - 3 months ago 22
Javascript Question

Rails js.erb append block link_to

I need to append a

link_to block
in, but I encountered some troubles.

Here is the
link_to block


<%=link_to user_create_question_sort_section_path, :remote=> true , :method=> :post do %>
<button class="btn glyphicon glyphicon-sort-by-attributes"></button>
<% end %>


It works fine and displays perfectly in html, but it would display wrongly if I use
js.erb
to append.

In js.erb I typed

$('#sort_btn').append("<%= j link_to user_create_question_sort_section_path, :remote=> true , :method=> :post do %><button class="btn glyphicon glyphicon-sort-by-attributes"></button><% end %>");


However, it displays like this

enter image description here

It seems took the
path
arg as name.

Answer

Wrap the link_to block into a partial and render it in your js.erb template.

# _link.html.erb

<%= link_to user_create_question_sort_section_path, :remote=> true, :method=> :post do %>
  <button class="btn glyphicon glyphicon-sort-by-attributes"></button> 
<% end %>

And in your template, render the link

# action.js.erb

$('#sort_btn').append("<%= render 'link' %>");