summaryrefslogtreecommitdiffstats
path: root/lib/Jaos/WebApp/Render/TT.pm
blob: 54d38970161b87a2b20b59677f9128a3359a8e3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package Jaos::WebApp::Render::TT;
use strict;
use warnings;
use Template ();
use File::Path ();
use Encode;


sub register
{
  my ($class, $app, $conf) = @_;

  # defaults
  $conf                 ||= {};
  $conf->{INCLUDE_PATH} ||= $app->appdir . '/template';
  $conf->{COMPILE_EXT}  ||= '.ttc';
  $conf->{COMPILE_DIR}  ||= $app->appdir . '/tmp';

  File::Path::mkpath($conf->{COMPILE_DIR});

  my $t= Template->new($conf);

  $app->add_renderer(
    tt => sub {
      my ($controller, $template, %options) = @_;
      my $output;
      $controller->stash->{c} = $controller;
      $t->process($template,  
        $controller->stash,
        \$output
      ) or die "$@";
      $controller->app->res->content_type('text/html');
      $controller->app->res->body(Encode::encode('utf-8',$output));
    }
  );

  $app->add_renderer(
    tt_raw => sub {
      my $output;
      $t->process(shift, undef, \$output);
      return $output;
    }
  );
}

=head1 NAME

Jaos::WebApp::Render::TT - Render output with Template Toolkit

=head1 SYNOPSIS

 package MyApp::Controller;
 use base qw/Jaos::WebApp/;
 sub startup
 {
   my $app = shift;
   # optional Template constructor options, See L<Template>
   my $tt_options = {}; 
   $app->load_plugin('Jaos::WebApp::Render::TT', $tt_options);
   $app->connect('/welcome/', controller => 'MyApp::Controller', action => 'welcome');
 }

 package MyApp::Controller;
 use base qw/Jaos::WebApp::Controller/;
 sub welcome
 {
   my $self = shift;
   $self->render( tt => 'welcome.tt');
 }

 sub raw
 {
   my $self = shift;
   my $html = $self->render( tt_raw => 'welcome.tt');
 }
 1;

=head1 DESCRIPTION

This is a L<Template> renderer for L<Jaos::WebApp>.

=head1 METHODS

=head2 register

Called by the L<Jaos::WebApp> plugin loader.

=head1 AUTHOR

Jason Woodward <woodwardj@jaos.org>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;