Topic: Require a template in another one

Hi,

I began to use rails this week, so I'm yet a beginner ! I find this is almost easy to learn, but now I got some problems that I want to solve before beginning seriously to developp something.

With php, I was used to separate my pages in 3 sections :

-Header
-Body
-Footer

The header is the part that contain all the top of each page (not only the <head></head> tag). I had only one template that was included in all pages.

The body was a part different for each page, it's the main part.

And finally, at the bottom, the footer that contain a copyright and everythin...

But now I want to do it with rails, and I don't find how because I'm not able to display more than one template at time, the one that's called automatically.

I tried to put <%= require "header.rhtml" %> but I get this error :

No such file to load -- header.rhtml

Thanks everyone smile .

Re: Require a template in another one

One very important concept to grasp at the beginning is accepting the Rails conventions. No doubt the Rails Way is different than what you did before, but in my case it was often better. I didn't realize that until much later.

In this case, instead of splitting the header and footer, the rails convention is to make a layout template which the primary template is embedded in.

For example, if you create a file here: app/views/layouts/application.rhtml it will be loaded automatically as the layout file for every view. You can put a "yield" statement in this layout file which will be where the other templates are placed.

Here's what application.rhtml could look like. Simplified for example:

<html>
<head>
  <title>My Site</title>
</head>
<body>
<h1>My Site</h1>
<%= yield %>
</body>
</html>

Of course, Rails also supports including protions of html. In this case you would create what is called a partial by putting an underscore before the view's name: app/views/my_controller/_foo.rhtml. You could then render this partial in the my_controller's views like this:

<%= render :partial => 'foo' %>

Yes, you could do this for header and footer, but I don't see a reason to since they are already in a separate layout file.

Railscasts - Free Ruby on Rails Screencasts

Re: Require a template in another one

Yes I see, you include the body to the model instead of including header and footer to the body...

It works all fine, thanks a lot big_smile !

Edit : Is there a way to mark a topic as solved ?

Last edited by Alexbad (2006-12-03 13:23:23)