views:

123

answers:

2

I'm working on a web-app without a framework right now, and I'm trying to structure it as a MVC app. The problem is, there are some technical aspects of MVC apps that escape me.

Primarily, how should a view be build? I'd like to use a markup language like eRuby or #haml, but I don't know how exactly they work and how to implement them in a non-Rails application.

How does the view get data from the model and directions from the controller? In Rails, this is all obfuscated. How can I implement this? What's the theory behind this? Do I make a connection to my database in the view and then use it freely there? Do I have it pass through another program aside from just the #haml renderer to give it data?

Thanks!

+1  A: 

Simple case:

ERB.new("your_template.erb").result(binding)

This will evaluate the template with the context of where it's called.

My preferred/simplistic way of doing this is to just call it inside the controller, and deal with the controller and view being a little merged.

If you don't want to do that, you need to create a view class, that has a method as follows:

def get_binding
  binding
end

Then create a new instance, setting all the instance variables as needed in the view, then call:

view = ViewClass.new
view.object = my_data_from_the_db
return [200, {…}, [ERB.new("your_template.erb").result(view.get_binding)] ]

Or… just give up an and use sinatra.

cwninja
This clears things up a bit – one thing: how do you stay strictly MVC and yet feed things to the View? Where do you process the view (to render as HTML) and how does the view get the variables from the model that it needs?
Isaac Hodes
Rails copies across all instance variables from the controller to the view (along with some 'magic' to delegate the helper_methods). There is no good reason the controller can't just create a view object and render it itself.
cwninja
+2  A: 

I don't yet have enough points to comment but to answer your question on cwninja's answer, in most cases you render the view form within a controller action. A controller gets a request, executes the right action and return's a response, in this case a rendered view as the response body. A simple example using haml could look like this:

class SomeController

 def some_action
   @foo = "bar"
   Haml::Engine.new(template).render(self)
 end
end

In this case instance variables setup in the controller will automatically be made available to the view since they are defined in the same context. Variables from the model will not be available as they shouldn't, however anything you can access from the controller action can be accessed from the view. Most templating systems also allow you to pass along a hash of local variables to the view, eg:

   Haml::Engine.new(template).render(self, {:foo => "bar"})

I hope this clears up some of your confusion :)

pmh
It does - thank you! This completely answers my question – cheers!
Isaac Hodes
Great, I'm glad I could help
pmh