Monday, January 19, 2009

Ramaze Multiple Pages With Linking

Having users have to switch between pages using the URL isn't particularly user friendly, so we'll add links to the pages to switch between them. Here's the code:

require 'rubygems'
require 'ramaze'

# This example is based on the previous "multiple pages" example.
# It has the same three methods (index, page1, and page2) but adds
# links on each page to the other two pages. For linking it uses
# the Ramaze Rs helper for linking within the same controller. The
# other item that is different is that instead of the content
# being in double quotes, we use the %{} form which is the same
# as the double quotes or as %Q{}. They just make it easier to
# include quotes in the string.
class MainController < Ramaze::Controller

# You can access it now with http://localhost:7000/
# This should output
# Hello, World!
# in your browser and provide links to the other two pages
def index
%{
Hello, World! <br/>
<a href="#{Rs(:page1)}">Page 1</a>
<a href="#{Rs(:page2)}">Page 2</a>
}
end

# You can access it now with http://localhost:7000/page1
# This should output
# "Page 1!"
# in your browser and provide links to the other two pages
def page1
%{
Page 1 <br/>
<a href="#{Rs(:index)}">Hello world</a>
<a href="#{Rs(:page2)}">Page 2</a>
}
end

# You can access it now with http://localhost:7000/page2
# This should output
# "Page 2!"
# in your browser and provide links to the other two pages
def page2
%{
Page 2 <br/>
<a href="#{Rs(:index)}">Hello world</a>
<a href="#{Rs(:page1)}">Page 1</a>
}
end
end

Ramaze.start



The initial comments pretty much spell out what's going on here. We've added a links on each page to the other two pages. Within each method, we've used the %{} form of the double quotes to simplify the strings (i.e. we don't have to escape all of the quotes). For the links themselves, we've used the Rs helper. This allows us to create a link within the same controller. Later, we'll use the R helper between controllers. You can read more about helpers on the Ramaze wiki.

As always, copy this into a text editor, save it (as say "link.rb"), and run it using either
ruby link.rb
or
ramaze link.rb
.

Let me know if you have questions or comments.

No comments:

Post a Comment