TT: Filters Versus Methods

Ovid on 2007-06-08T14:00:48

Can someone tell me why I would want to use a filter instead of a vmethod when using Template Toolkit? Let's say I need ucfirst. Here's a filter:

[% some_var FILTER ucfirst %]

Or the more concise:

[% some_var | ucfirst %]

Frankly, I don't get this. I'd rather write:

[% some_var.ucfirst %]

In fact, it's trivial to provide that:

use Template::Stash;    
$Template::Stash::SCALAR_OPS->{ucfirst} = sub { ucfirst shift };

The only advantage I can see for filters is that I can call them on constants:

[% "hello" | ucfirst %]

You can't do that with vmethods (a shame). However, method syntax seems far more natural. Admittedly, filters are great when I have a multi-line block of text:

[% FILTER html_para %]
Mary had a little lamb.

Support Planned Parenthood.
[% END %]

So, other than this compelling reason, why would filters be preferable? They're just one more thing to remember.


TT: Filters Versus Methods

draegtun on 2007-06-08T14:42:31

U can also apply FILTERs to blocks....

[% PROCESS some_block | upper %]

/I3az/

Mea Culpa Cum 20/20 Hindsight

abw on 2007-06-09T06:38:40

The short answer is that it's a design misfeature.

As you note, FILTER can be used as a block directive whereas vmethods can't. But other than that syntactic difference, they *should* both hook into the same backend components so that filters and text vmethods are fully interchangeable.

In TT2 they're not, but they will be in TT3.