Sunday, February 8, 2009

Using Different .xhtml Files for Different Pages

In this post, I'll show how each method in a controller can use a different .xhtml inside of the master page.xhtml. We'll start with the code from our last post, Passing Data From Views To Controllers. Here's the ruby code usedifferentxhtml.rb:

require 'rubygems'
require 'ramaze'

# This example is based on the previous "passing data to views" example.
# It has the same three methods (index, page1, and page2) but each of
# these only sets the title. Everything else comes from either the
# page.xhtml file or the individual index.xhtml, page1.xhtml, or
# page2.xhtml.
class MainController < Ramaze::Controller

# Use page.xhtml in the view directory for layout
layout :page

# You can access it now with http://localhost:7000/
# All we're going to do is set the title in here and
# everything else will come from our index.xhtml file.
def index
@title = "Index Page"
end

# You can access it now with http://localhost:7000/
# All we're going to do is set the title in here and
# everything else will come from our page1.xhtml file.
def page1
@title = "Page 1"
end

# You can access it now with http://localhost:7000/
# All we're going to do is set the title in here and
# everything else will come from our page2.xhtml file.
def page2
@title = "Page 2"
end
end

Ramaze.start


Here's our page.xhtml which is the same as in our last post:

<html>
<head> <title>#@title</title> </head>
<body>
<h1>#@title</h1>
#@content
<h5> Powered by Ramaze </h5>
</body>
</html>


Here's our index.xhtml:

Hello, World! <br/>
<a href="#{Rs(:page1)}">Page 1</a>
<a href="#{Rs(:page2)}">Page 2</a>


Here's our page1.xhtml

Page 1 <br/>
<a href="#{Rs(:index)}">Hello world</a>
<a href="#{Rs(:page2)}">Page 2</a>


and finally, out page2.xhtml

Page 2 <br/>
<a href="#{Rs(:index)}">Hello world</a>
<a href="#{Rs(:page1)}">Page 1</a>


As you can see, all we've really done is move some code from our controller to the view. Ramaze uses the templating system Ezamar by default and that is what will be used here to put everything together.

One additional thing to note, if you have a second controller and it's mapped to say map 'xyz', then you will have to either put the templates in the view/xyz or name them xyz__index.xhtml, xyz__page1.xhtml, etc.

No comments:

Post a Comment