Ian H Ian H - 2 months ago 7x
Javascript Question

Ruby on Rails - modifying part of embedded Ruby in .js.erb

I'm working on a single-page site and have gotten the ajax loading of templates to insert into the content part of the site working. However, I'm having trouble doing this with multiple templates, using a parameter.

I have 5 templates, shared/blog, shared/projects, etc.

In my controller, I'm doing an AJAX call to 'replace'

pages = ['blog', 'projects', 'resume', 'gallery', 'contact']

def replace
@content = params[:content]
if not pages.include? content
content = 'blog'
respond_to do |format|

In replace.js.erb, I have this code:

$(".content_inner").html("<%= j render(:partial => 'shared/blog') %>");

I have kept it just saying 'shared/blog' because it works for loading the blog if I keep the embedded Ruby static like that. However, I can't figure out how to replace the 'blog' part of 'shared/blog' in here to whatever is in the @content variable. I've tried things like #{content}, but to no avail.

(It does receive the content variable correctly, the issue is just with using it)

Any help would be appreciated!



String interpolation requires double quotes. You're after:

$(".content_inner").html("<%= j render("shared/#{@content}") %>");

A few notes:

  • The :partial => hasn't been necessary for years in Rails. Just use render <partial_name>.
  • Rails already comes with a place to store your shared partials: app/views/application. You should move your shared partials there, and then you can render them simply by using render(@content). This is important to how Rails works, because it allows you to override the partial in controller-specific view paths. For example, calling render("blog") will render app/views/<controller_name>/blog.js.erb if it exists, and then fallback to app/views/application/blog.js.erb otherwise.