Rendering a view partial via javascript/jquery

Hi guys,

I’m using masonry.js on a project and want to insert a div containing a form. I would like to insert this div via jquery in the middle of a set of divs (the reason I’m doing it this way is because masonry doesn’t easily allow a fixed element to be placed and the divs to flow around it). In the js.erb file, I have been trying to accomplish this with the following:

$('#masonry').before("<%= j render 'black_box %>);

This causes a javascript error. I’ve tried variations using escape_javascript and/or html_safe but none seem to work. Thanks!

There could be something else wrong, but upon first glance (and if this is a direct quote from your code) you aren’t closing out the quotes.

Maybe try:

$('#masonry').before("<%= j render 'black_box' %>");

@dolphorama that actually wasn’t the problem (it wasn’t a paste from the code). The error is complaining about ‘render’: undefined methodrender’ for #<#Class:0x007f9e5545b2a8:0x007f9e5552dfc8>`

I’m sure it’s something simple, but I haven’t been able to track it down yet. Thanks!

Not 100% but try render partial: ‘black_box’

Is this a .js.erb file in your views folder that your requesting during ajax? Or is this something you’ve placed in assets? If its the latter, you should move all the ruby bits out of the js files, and instead place them inside of a script tag in a .html.erb view.

@seangriffin Yes that was the solution! The js.erb file in this case was actually in the assets folder. By moving the ruby to the view, my problem was solved. Why does it make a difference? Thanks again!

Render is a method that exists on ActionView::Base. Assets aren’t compiled as an instance of ActionView.