[Templates] "in array" function?

Sean McAfee eefacm at gmail.com
Wed Mar 5 23:14:13 GMT 2008


On Wed, Mar 5, 2008 at 2:46 PM, Chris Petersen <lists at forevermore.net>
wrote:

> On Mar 5, 2008, at 12:40 PM, Andrew Marold wrote:
> > How about [% IF foo.match('(foo|bar)') %] ?
>
> That would work, assuming you added anchors to the regex and I'm only
> ever matching against static lists and not pre-defined variables
> (which in this case is the likely scenario)..  but would also require
> the template designers to understand regex (and a large reason to move
> to TT is so the devs who understand regex don't have to do html work).
>
> However, if that's the only option, it's easy enough to teach simple
> regex like this.  Thanks.
>

Probably a more foolproof solution for nonprogrammers is just to go with the
vmethod.

$Template::Stash::SCALAR_OPS->{isOneOf} = sub {
    my $str = shift;
    $str eq $_ and return 1 for @_;
    return 0;
};

[% IF var.isOneOf('foo', 'bar'); ...; END %]

Experience has taught me to approach regexen with a great deal of caution.
It's so common to see errors like:

if ($var =~ /^foo|bar|baz$/) { ... }

In fact, there are several such in the TT2 codebase itself right now:

$ grep -r '/\^[a-z]*|' .
./Template/Context.pm:    if ($args[0] =~ /^on|1$/i) {
./Template/Context.pm:    elsif ($args[0] =~ /^off|0$/i) {
./Template/Directive.pm:        die \$_tt_error if \$_tt_error->type =~
/^return|stop\$/;
./Template/Stash.pm:    if ($type =~ /^scalar|item$/) {
./Template/Stash.pm:    elsif ($type =~ /^list|array$/) {

Hmm.  I could have sworn I noted some of these before, but I suppose I
mislaid my notes before I acted on them.  Guess I'll check in a fix shortly.


--Sean
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.template-toolkit.org/pipermail/templates/attachments/20080305/9cc5c812/attachment-0001.htm 


More information about the templates mailing list