1

When users go to my site, I want to render both the index.html.haml, as well as the index.js.haml. (I'm trying to get my JS out of the view.)

Currently, it just renders the html. Adding a respond_to block with both html and js just renders html of course.

How do I do this? Is there a better way? I don't want to include the JS in /assets/js, because ruby gets executed in the JS.

1
  • javascript isn't rendered btw (just a heads-up). Rendering is displaying content to the user. Commented May 16, 2012 at 14:00

1 Answer 1

4

A rails controller action can only respond to one HTTP request at a time, and even if it could respond to more than one the JS is requested from the HTML the initial request made any way (so it's a separate request).

If you'd like to keep your Javascript in another file for clarity you could create a partial and load it in that way.

In the view that responds to the controller action with @my_var passed to the partial (./views/mycontroller/my_action.html.erb):

<%= render 'my_action_js', :my_var => @my_var %>

And the partial (./views/mycontroller/_my_action_js.html.erb)

<script type="text/javascript">
    alert(<%= my_var %>);
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

@KreeK, is it Rails-like to do this with that javascript partial being an ajax polling request to get data from the db and then render it?
@yeenow123 not sure if it's the Rails-way :) but I don't see anything wrong with it. My general rule is if it's a small amount of data pass it along with the original request, if it's larger and you want to get something on the page so the user doesn't bail then load it after the fact.

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.