Topic: Making controller/view variables visible to javascript?

I've done a bunch of Rails in the past, but I'm new to the business of adding client-side scripting to fancy-up the behavior of some of my pages.  My question is, what's the "approved method" (if there is one) for exposing values that you have in a controller action or in a view to any javascript on the page?  Specifically, I'd like to be able to do this at the top of a view:

<% @menuItem = "blog" -%>

And then later, in scripting (w/ Prototype):

document.observe('dom:loaded', function() {
  $(menuItem).invoke('addClassName', 'activeMenuItem');
});

Basically, when the page loads I want the script to take care of tweaking the CSS class on the designated item in my template's menu bar so the user knows what page they're on.  I'd like to be able to do it through a simple variable assignment in the view, because that way it's trivial to have lots of sub-pages of a given area of my website all appear to the user as part of the same menu item, I just have no idea what the "right way" is of exposing that menu item id string to the script.

Re: Making controller/view variables visible to javascript?

Nevermind, I figured it out.  My problem was not understanding that the view gets executed (and its output cached) _before_ the template executes.  And, the template automatically has access to any controller instance variables, which the view can create and set.  So, I almost had it with the above.  Her's what worked for me:

View:
<% @menuItem = "whatever" -%>

Template:

<script>
document.observe('dom:loaded', function() {
  <%= "setMenuItem(\"#{@menuItem}\");" %>
});
</script>

...where setMenuItem() is defined in my application.js.  This works, but I'm not super happy with it because I'd prefer not to have to have any explicit javascript in the rendered html that goes to the browser.  If anyone has a cleaner solution for how I can hide the entire document.observe() call inside my application.js, but still give it access to @activeMenuItem, I'd love to see it.

Last edited by cloister (2009-04-22 19:11:54)