in reply to Template Toolkit 2 and subroutines

There are all kinds of things you CAN do in TT, but that doesn't mean you should do them. It sounds like you want macros (which are in the docs), but if these are doing actual Perl processing (as opposed to just encapsulating a display rule) you'd be better off doing it before running the template or at least putting it in a plugin.

If you start shoving lots of subroutines and stuff into your templates, you'll lose the separation that is the whole point of TT. On the other hand, if you really think this is a more appropriate way to write your templates, maybe you should use an in-line Perl templating tool like Text::Template.

Replies are listed 'Best First'.
Re: Re: Template Toolkit 2 and subroutines
by marcink (Monk) on Oct 09, 2001 at 18:12 UTC
    There are all kinds of things you CAN do in TT, but that doesn't mean you should do them.

    I'm quite well aware of that, but thanks for reminding anyway ;)

    What I want to do is really simple output processing (like substituting   for spaces in menus). I think that's something I can safely do in a template -- if not, I'll be happy to hear why before I go too far in a wrong direction :)

    I checked merlyn's examples. Here are the results:

    Template:

    --cut here-- [% MACRO tr_test BLOCK %] join ':', @_; [% END %] [% PERL %] $stash->set( 'tr_test_2', sub { join ':', @_ } ); [% END %] 1: [% tr_test( 'test', '1' ) %] 2: [% tr_test_2( 'test', '2' ) %] --cut here--


    And the result:

    --cut here-- 1: join ':', @_; 2: test:2 --cut here--


    So the latter does exactly what I need. Thanks for both answers.

    -marcink
      What I want to do is really simple output processing (like substituting   for spaces in menus). I think that's something I can safely do in a template -- if not, I'll be happy to hear why before I go too far in a wrong direction :)
      Oh, then be sure to read Template::Filters to see how to do that properly. In fact, there might already be a filter in the standard collection to do that!

      -- Randal L. Schwartz, Perl hacker

      What I want to do is really simple output processing (like substituting   for spaces in menus).

      Isn't that what FILTERs are for?

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you don't talk about Perl club."

      In addition to the use of filters, you can pass a reference to any sub in as part of the stash. I sometimes pass in a URI escape subroutine from Apache::Util and use it like this in a template: [% uri(foo.bar) %]