Brian
Brian

Reputation: 6071

Rails: What is the proper way to render a partial in a js.erb file 3.2.7

I've read posts saying that it is not possible to render a partial in a js.erb file. What is the proper way to accomplish this?

I am trying to use jquery ui to render a contact form in a dialog box.

var contactHtml = $('<div></div>').html("test").dialog({
    autoOpen: false,
    title: 'hi'
});

Thanks

Upvotes: 1

Views: 1566

Answers (3)

Brian
Brian

Reputation: 6071

I still used a partial for my form, but I rendered it with ajax.

In my js.erb file

  var contactHtml = $('<div></div>').dialog({
    autoOpen: false,
    title: 'Get a Free Estimate',
    minWidth:400,
    close: function(){$(this).empty();}
});
$('#consultation').click(function(){
    $.get('/contact_form', function(data){
        contactHtml.append(data);
    });
    contactHtml.dialog('open');
    return false;
});

Routes:

  match "contact_form" => "application#contact_form", :via => :get

Application Controller:

  def contact_form
  @contact = Refinery::Contacts::Contact.new
  render :partial => "/contact_form", :locals => {:contact => @contact}
  end

Upvotes: 1

Kyle C
Kyle C

Reputation: 4097

       $('<div></div>').html("<%= j(render :partial => 'example/file') %>")

just remember to escape your render call with j (synonymous with escape_javascript). You will use this approach a lot when you are dealing with ajax calls.

Edit

If you are attempting this from your assets folder, this is not possible and you will get the undefined method render error. Here is a similar Question for more details

Upvotes: 3

ghaydarov
ghaydarov

Reputation: 11

Generally you can do something like below in your js.erb:

$("yourclass").javascript_action("<%= escape_javascript(render('partial_name', :local_var_name => @local_var_name)) %>");

and in your partial pass locals:

  <%= render 'partial_name', :local_var_name => local_var_name %>

Hope this helps!

Upvotes: 0

Related Questions