/*For rotating the ads */

Wednesday, September 17, 2008

Layouts and content_for


In rails application usually we will be using <%=yield%> for dispalying the content in the block.
Our Rails Layout will something like this


<html>
<title>Content_for</title>
<head>
<%=stylesheet_link_tag 'application'%>
</head>
<body>
<div id='header'> </div>
<div id='content'><%=yield%></div>
<div id='sidebar'> </div>
<div id='footer'> </div>
</body>
</html>

If you want to change something in the layout on a per-template basis, content_for is your answer! This allows templates to specify view code that can be placed anywhere in a layout.
Now we want to include one more stylesheet for our index.html.erb,that should be used only for index.html.erb & not for other.

Assume there are two controllers

1.light

2.image


Both controllers are using the same layout,but each controllers need different css & stylesheets.For this purpose we will be using content_for

Example


In this example,content_for have been used & it is called in the layout itself,so the brower is showing the block content.

Code



Browser



Similarly we can use this for diff controllers.

1.Define our Layout


View code



2.Define content_for in light controller


View code


Now content_for has been defined for the light controller for index action.


Here the css & js files have used only for index.html.erb.so other actions wont be able to access the style & css

3.Define content_for in image controller


View code


Now we have defined content_for in image controller for the action new

4.Output of content_for


Just view the figures below.

Light controller



Image controller



Page source for light controller



Page source for image controller



Finally content_for has been implemented


Kind notice this tutorial has been created & tested in rails 2.1.0

0 comments:

Favouite quote

"For most of my life, I've thought that doing good for someone didn't mean you would receive any commendation for an act of kindness -- until now,"
Jerry Lewis

About This Blog

This is my tech blog.Its mainly about Ruby on Rails programming.People laugh because i am different.And I laugh because all are same.Thats called attitude.I am a webdesigner too.


  ©Free Blogger Templates Columnus by Ourblogtemplates.com 2008 Template customized as per wordpress template 5thirtyone

Back to TOP