Ruby on Rails includes the concept of layouts, which enable you to specify that outer framework that pages in your application will be rendered within. Most view libraries support includes, which enable you to do things like this:
My page
Do stuff here.
Layouts are a bit nicer in that you don’t even have to maintain the includes on each page. One nice feature of layouts is that if you create a variable within a page, it will be accessible when the enclosing layout is rendered. So you can have a layout like this:
<%= @page_title %>
<%= yield :layout %>
And then a page like this:
<% @page_title = "My Web Page">
<%= @page_title %>
This is my web page.
The page title variable that’s set on the page will be visible to the layout, enabling you to use titles specific to each page even though they’re all rendered in the same layout.
Now to get to my point. What’s the best (or most accepted) way to link to include page-specific JavaScript in a Ruby on Rails application? Script references belong in the page header, not in the page body. The page header lives in my layout file. I could just embed the script within the specific pages, but that’s cheating, and I don’t like to cheat.
The solution I came up with involves creating an external JavaScript file for every page that has its own scripts. Rails provides a helper method called javascript_include_tag
that builds a link tag to a named JavaScript file, as long as it’s in the public/javascripts
directory in your application. So to include public/javascripts/application.js
, you just use:
<%= javascript_include_tag "application" %>
Right now, I’m taking advantage of this feature along with the way variable scoping works with layouts and views to handle page-specific Javascript. In my layout file, I have the following:
<% if @page_specific_scripts_in %>
<%= javascript_include_tag @page_specific_scripts_in %>
<% end %>
In my view, I have the following:
<% @page_specific_scripts_in = "controller_index" %>
And then in public/javascripts
I have controller_index.js
. This works, but I can’t help but wonder if there’s a better way.
Dead in the water
Looks like the site was down for a bit due to some server configuration mistakes that I made. Note to self, don’t reference
Apache::Registry
in your server configuration when you don’t have the Perl module installed.