Passing variables between views and layout templates with Ruby on Rails
One of the most useful discoveries I have made with Rails is the ability to pass variables from a layout to a view and vice versa.
This means I can set Body ID's, for example, in my views that are used in the layout. To achieve this I would put the following in my layout:
<body id="<%= @bodyid %>">
And in my view I would put at the top:
<% @bodyid = "body_home" %>
Obviously it doesn't have to be a Body Id, it could be a page title, description, rss feed path, anything. This is really powerfull because it allows you to take advantage of the template system with no need to repeat the code on every page.
You may also have noticed that it doesn't matter that the layout calls the variable before the view, Rails is clever like that. Also, it wont error if the variable doesn't get set in the view.
Personally I find setting Body IDs on pages to be really poweful in CSS styling. You can use the Body ID to highlight navigation elements to show the page you are on or render completely different page layouts. Find out more about how I do this.
About
Paul is a Rails developer for Kyan web agency.
Checkout his ramblings about music, what he's listening to and his other random thoughts.
He also writes on the Kyan blog.
More snippets
Take a look in the archive
Need a website?
Your best bet is to contact Paul's employer. Make sure to check out the portfolio of work.
Hosting
I recommend hostingrails.com
Recommended Reading
Contact
my name at gmail.com
2 comments made
Neat. I was abusing content_for to get a similar effect…
For example…
In the layout:
<body>
In the view:
<% give_focus ‘user_username’ >
< form_for :user do |form| >
<= form.text_field :username %>
…
In the helper:
def give_focus(element_id)
content_for :onload do
“document.getElementById(‘#{element_id}’).focus()”
end
end
——
Curiously, in give_focus() using braces instead of do…end didn’t work, not quite sure why.
Not having much luck with putting code in my comments, sorry for the mess.
Got something to say?