1

My problem is the following:

I want to use <%render => "xx"%> in a js.erb file - so I can't put it in my assets folder because render doesn't work in asset files.

I already tried to name it index.js.erb to get rails to include it automatically(it lies in the view folder, see below) but I guess that doesn't get included because I deleted the require_tree line in my admin.js(It's the "application.js" for my admin namespace). I can't use require tree simple because I don't want every js file in assets/javascripts/admin to be included.

I got my js file here:

views/admin/benefits/index.js.erb

I want to use it in the following view:

views/admin/benefits/index.html.erb

Am i overcomplicating something here? If not, how would I include it in my view? If it matters: I use rails 4.

1
  • Did you get this solved? I've got the same problem. I'm trying to use render and moved the .js.erb file to my Views folder.. but it now seems like the file isn't included in the asset pipeline at all. Commented Oct 12, 2014 at 11:45

2 Answers 2

1

Move it to assets and add a optional yield to the head of your layout file.

In your layout file

<% if content_for?(:javascripts) %>
  yield(:javascripts)
<% end %>

In your view

<% content_for :javascripts do %>
  <%= javascript_include_tag 'benefits/index' %>
<% end %>

I think you are misunderstanding what the use of this file. js.erb files allow you to use Ruby in your JavaScript file. You can't actually render this file. You can look here to get a better understanding for why it is used.

Sign up to request clarification or add additional context in comments.

3 Comments

I updated my answer to explain what js.erb files are used for.
I don't want to render the js file. I want to render a partial in a js call, simple as that. I could put the whole js code directly in my view and it would work but since that not good style I want it in an external js file.
Just have the js function return HTML from the js and insert it into the DOM.
0

js.erb files are used with respond_to block, allowing the controller to respond to your Ajax request.

def create
  respond_to do |format|
    ...
    format.js
    ...
  end
end

You then have a corresponding app/views/users/create.js.erb view file that generates the actual JavaScript code that will be sent and executed on the client side.

$("<%= escape_javascript(render @user) %>").appendTo("#users");

More info here

In your case, you can define the javascript code in assets/javascript/admin/benefits.js, for example. Include only this file in application.js like:

//= require admin/benefits

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.