Model objects instead of drops?

133 views
Skip to first unread message

bank...@gmail.com

unread,
Mar 26, 2007, 2:19:30 AM3/26/07
to Liquid Templates
Is there a quick way to nake Template use plain old model objects
instead of drops? I naively tried passing a model object and I got
Liquid error: undefined method `to_liquid' whenever I tried to output
a property value from it.

I tried making an AutoDrop to work around this but it only works
{{ one.property }} deep. For instance {{ this.will.not.work }}
because this.will returns a model object, rather than yet another
drop.

I see a few other people have run into this issue and the answer seems
to be "Wrap your model classes with Drop classes" which means
declaring your model object properties in two places.

Why not just make liquid work with plain old model classes? Wouldn't
that be more DRY?

Matt Lyon

unread,
Mar 26, 2007, 3:35:22 AM3/26/07
to liquid-t...@googlegroups.com
You're missing the point of Liquid, which is to have templates that
are eval-safe. Meaning the template doesn't modify the underlying
data model(s). The idea is to prevent the template from doing things
like {% article.destroy %}, or some of the more nefarious things you
could do in erb or almost any of the other ruby templating languages.

If you add this to your models, or even extend ActiveRecord::Base,
and you can pass a model's attributes to liquid for free.
Associations are not included however:

def to_liquid
self.attributes.stringify_keys
end

DRY-ing up your drops is fairly straight-forward. As always, Rick's
code in Mephisto provides a good starting point.

If you're looking for some of the 'it just works' magic that rails
has with your drops and your models' associations however, you're
going to be disappointed. Writing that kind of thing will become a
major headache as you descend into ActiveRecord's association
introspection code. And then you'll discover a couple of instances
where you _don't_ want the magic.

Matt

Reply all
Reply to author
Forward
0 new messages