Saturday, September 4, 2010

Ramaze and Partial Rendering

Over on the Ramaze list, we had quite a conversation going on about the MVC paradigm. In response to that, I ended up doing some research on partial rendering (rendering a piece of a view using another view). I ended up writing some code and it's available on GitHub here. The original code was generated using ramaze create RenderPartial and then modified to its present form.


class MainController < Controller
# the index action is called automatically when no other action is specified
def index
@title = "Welcome to Ramaze!"
end

def page_1
@title = "Page 1"
@colors = ["blue", "brown", "hazel"]
end

def page_2
@title = "Page 2"
@colors = ["blue", "brown", "hazel"]
end

end



The colors are predefined here in the controller, but in a real example, you would normally get them from a model probably from a database. The use of colors itself comes from the question in the email trail about dolls and the different color of eyes they could be. There's nothing particularly complex in here, we've seen it quite a few times, there's an index method and then two additional page methods where the latter are pretty much exactly the same.

The views are where the interesting part is though. Here's the page 1 view contained in view/page_1.xhtml


<p>
Page 1
#{ render_partial :color }
</p>


and the page 2 view, view/page_2.xhtml


<p>
Page 2
#{ render_partial :color }
</p>



and finally, the view/color.xhtml, the partial that we render:


<ul>
<?r @colors.each do | color | ?>
<li> #{color} </li>
<?r end ?>
</ul>


Here, we simply take the colors that were defined in the controller methods and use them to generate a list (obviously, we could have done whatever we wanted with them). The lines in the two page views #{ render_partial :color } tells the view to fill in this spot with the view/color.xhtml code. Although, we haven't here, you can also pass parameters to the partial. Here's a post that shows how to use that feature.

Hopefully, this is all pretty clear, but if not, as always, feel free to leave questions in the comments section.

No comments:

Post a Comment