[Templates] Filters + replace

Garrett, Philip (MAN-Corporate) Philip.Garrett@manheim.com
Fri, 28 Jul 2006 10:12:38 -0400


andrew3@black1.org.uk wrote:
> I am trying to expand some text from a number of files.
> Each file has an announcement in it. The first line is aubject
> and the rest text.
>=20
> I would like a filter that
>   - takes the first line and makes it <h2>....</h2>
>   - processes the rest in the manner of html_para
>=20
> A number of ways of hacking thos
>  - Is there are filter that does something along these lines

Not to my knowledge.

>  - is it possible to create my own filter - cant see description of
>    how to do it

Yes:

  my $tt2 =3D Template->new();
  # define a filter "foo" that wraps its input in <foo> tags
  $tt2->context->define_filter( 'foo', sub { return "<foo>$_[0]</foo>"
});

  my $template =3D qq{
        [% "bar" | foo %]
  };
  $tt2->process(\$template);

>  - I have tried to do [ INCLUDE filename | replace( 'soemregex',
>    '<h2>$1</h2> )
>    but the $1 bit doesnt seem to work

Backreferences don't work with the TT2 replace filter.  You could assign
the contents of $filename into a variable, and then get matches using
the match() scalar vmethod:

  [% text =3D INCLUDE "${filename}" %]
  [% matches =3D text.match('(?s)^([^\n]*)\s*(.*)') %]
  <h2>[% matches.0 %]</h2>
  [% matches.1 | html_para %]

Regards,
Philip