Skip to content

Passing variables between views and layout templates with Ruby on Rails

Posted on 03 April 2006

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.

View the snippets archive ››

2 comments made

Mike Tunnicliffe commented on 09 Dec 07 at 19:41
Neat. I was abusing content_for to get a similar effect… For example… In the layout: <body><= yield :onload >“>

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.
Mike Tunnicliffe commented on 09 Dec 07 at 19:43

Not having much luck with putting code in my comments, sorry for the mess.

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com