views:

87

answers:

1

How can I render only a specific BLOCK in a template?

Suppose I have this BLOCK in text.tt, a Template Toolkit file:

[% BLOCK someblock %] some block test blah blah blah [% END %]

I want to be able to use process() to handle just that portion:

$tt->process("text.tt/someblock", {...}, {...});

Is this the right way to handle this?

+5  A: 

I think its the EXPOSE_BLOCKS option that you maybe after?

use strict;
use warnings;
use Template;

my $tt = Template->new({
    INCLUDE_PATH  => '.',
    EXPOSE_BLOCKS => 1,
});

$tt->process( 'test.tt/header', { tit => 'Weekly report' } );

for my $day qw(Mon Tues Weds Thurs Fri Sat Sun) {
    $tt->process( 'test.tt/body', { day => $day, result => int rand 999 } );
}

$tt->process( 'test.tt/footer', { tit => '1st Jan 1999' } );

 

test.tt:

[% BLOCK header %]
[% tit %]
[% END %]

[% BLOCK body %]
* Results for [% day %] are [% result %]
[% END %]

[% BLOCK footer %]
Correct for week commencing [% tit %]
[% END %]

 

Will produce this report (with random numbers):

Weekly report

  • Results for Mon are 728

  • Results for Tues are 363

  • Results for Weds are 772

  • Results for Thurs are 864

  • Results for Fri are 490

  • Results for Sat are 88

  • Results for Sun are 887

Correct for week commencing 1st Jan 1999

 

Hope that helps.

/I3az/

draegtun
Thanks! Do you know where I can find a complete list of Template Toolkit config options? EXPOSE_BLOCKS isn't mentioned on this list: http://template-toolkit.org/docs/manual/Config.html
Sam Lee
That is probably the best list but unfortunately like you noticed EXPOSE_BLOCKS is missing from it :( I probably picked up EXPOSE_BLOCKS from the Perl Template Toolkit book (http://template-toolkit.org/book.html). Just flicking thru index it says page 69... hmmm example is pretty bare but it is mentioned there.
draegtun