Amazon.com Widgets MVC Blasphemy | t+1: Matt Wilson's blog

MVC Blasphemy

I just put HTML code into my data model. I have a list-of-objects page. Each object is an instance of an object defined in my data model, derived from a row in a database. Each object needs a pretty link drawn that object’s detailed-view page. So I added a property on my object:
class Message(SQLObject):
    def _get_view(self):
        "Draw a link to the view page for this message."
        return cElementTree.XML("""<a href="/details/%d">VIEW</a>""" % self.id)
    # Lots of other stuff snipped out.

This is now what my kid template looks like:

        <tr py:for="m in messages">
            <td py:for="col in columns" py:content="getattr(m, col)">MESSAGE STUFF</td>

I pass in messages and columns; messages is a list of objects and columns is a tuple of strings that map to attributes or properties, like “view”.

I’m happy with this decision. I know I could have manipulated the messages or created some new classes in my controller, but I couldn’t really see any advantage. This way works.

I just don’t want anyone else doing this :)

2 Comments »

  1. Kevin Dangoor said,

    December 20, 2007 @ 9:12 am

    This is certainly the quickest and easiest way to do it. No question… I will say that it doesn’t have to be much harder to have it separate though… consider a function like this:

    @dispatch.generic()
    def get_view(obj):
    pass

    @get_view.when(”isinstance(obj, Message)”)
    def message_view(obj):
    return “”

    You have the added overhead of the generic function, but then everything else is just a function with a decorator that says when to apply that function. And this approach can be extended as much as you want…

    Python provides a great many ways to do things succinctly, no? :)

  2. matt said,

    December 20, 2007 @ 10:01 am

    I’ll study that until it makes more sense. I’m not familar with generic functions in python. I love them in common lisp though.

    I posted this entry hoping that I would get some feedback on the right way to do it. Thanks!

RSS feed for comments on this post · TrackBack URI

Leave a Comment