Debian Codegraph @

lib/Dancer2/Template/TemplateToolkit.pm

raw
1 # ABSTRACT: Template toolkit engine for Dancer2
2
3 package Dancer2::Template::TemplateToolkit;
4 $Dancer2::Template::TemplateToolkit::VERSION = '2.2.2';
5 use Moo;
6 use Carp qw<croak>;
7 use Dancer2::Core::Types;
8 use Path::Tiny ();
9 use Scalar::Util ();
10 use Template;
11
12 # Override to use a different Template::Toolkit base class
13 has 'template_class' => ( is => 'ro', default => 'Template' );
14
15 with 'Dancer2::Core::Role::Template';
16
17 has '+engine' => ( isa => InstanceOf ['Template'], );
18
19 sub _build_engine {
20 my $self = shift;
21 my $charset = $self->charset;
22 my %tt_config = (
23 ANYCASE => 1,
24 ABSOLUTE => 1,
25 length($charset) ? ( ENCODING => $charset ) : (),
26 %{ $self->config },
27 );
28
29 my $start_tag = $self->config->{'start_tag'};
30 my $stop_tag = $self->config->{'stop_tag'} || $self->config->{end_tag};
31 $tt_config{'START_TAG'} = $start_tag
32 if defined $start_tag && $start_tag ne '[%';
33 $tt_config{'END_TAG'} = $stop_tag
34 if defined $stop_tag && $stop_tag ne '%]';
35
36 Scalar::Util::weaken( my $ttt = $self );
37 my $include_path = $self->config->{include_path};
38 $tt_config{'INCLUDE_PATH'} ||= [
39 ( defined $include_path ? $include_path : () ),
40 sub { [ $ttt->views ] },
41 ];
42
43 my $tt = $self->template_class->new(%tt_config);
44 $Template::Stash::PRIVATE = undef if $self->config->{show_private_variables};
45 return $tt;
46 }
47
48 sub render {
49 my ( $self, $template, $tokens ) = @_;
50
51 my $content = '';
52 my $charset = $self->charset;
53 my @options = length($charset) ? ( binmode => ":encoding($charset)" ) : ();
54 $self->engine->process( $template, $tokens, \$content, @options )
55 or croak 'Failed to render template: ' . $self->engine->error;
56
57 return $content;
58 }
59
60 # Override *_pathname methods from Dancer2::Core::Role::Template
61 # Let TT2 do the concatenation of paths to template names.
62 #
63 # TT2 will look in a its INCLUDE_PATH for templates.
64 # Typically $self->views is an absolute path, and we set ABSOLUTE=> 1 above.
65 # In that case TT2 does NOT iterate through what is set for INCLUDE_PATH
66 # However, if its not absolute, we want to allow TT2 iterate through the
67 # its INCLUDE_PATH, which we set to be $self->views.
68
69 sub view_pathname {
70 my ( $self, $view ) = @_;
71 return $self->_template_name($view);
72 }
73
74 sub layout_pathname {
75 my ( $self, $layout ) = @_;
76 return Path::Tiny::path(
77 $self->layout_dir,
78 $self->_template_name($layout),
79 )->stringify;
80 }
81
82 sub pathname_exists {
83 my ( $self, $pathname ) = @_;
84 my $exists = eval {
85 # dies if pathname can not be found via TT2's INCLUDE_PATH search
86 $self->engine->service->context->template( $pathname );
87 1;
88 };
89 $self->log_cb->( debug => $@ ) if ! $exists;
90 return $exists;
91 }
92
93 1;
94
95 __END__
96
97 =pod
98
99 =encoding UTF-8
100
101 =head1 NAME
102
103 Dancer2::Template::TemplateToolkit - Template toolkit engine for Dancer2
104
105 =head1 VERSION
106
107 version 2.2.2
108
109 =head1 SYNOPSIS
110
111 To use this engine, you may configure L<Dancer2> via C<config.yaml>:
112
113 template: "template_toolkit"
114
115 Or you may also change the rendering engine on a per-route basis by
116 setting it manually with C<set>:
117
118 # code code code
119 set template => 'template_toolkit';
120
121 Most configuration variables available when creating a new instance of a
122 L<Template>::Toolkit object can be declared inside the template toolkit
123 section on the engines configuration in your config.yml file. For example:
124
125 engines:
126 template:
127 template_toolkit:
128 start_tag: '<%'
129 end_tag: '%>'
130
131 (Note: C<start_tag> and C<end_tag> are regexes. If you want to use PHP-style
132 tags, you will need to list them as C<< <\? >> and C<< \?> >>.)
133 See L<Template::Manual::Config> for the configuration variables.
134
135 In addition to the standard configuration variables, the option C<show_private_variables>
136 is also available. Template::Toolkit, by default, does not render private variables
137 (the ones starting with an underscore). If in your project it gets easier to disable
138 this feature than changing variable names, add this option to your configuration.
139
140 show_private_variables: true
141
142 B<Warning:> Given the way Template::Toolkit implements this option, different Dancer2
143 applications running within the same interpreter will share this option!
144
145 =head1 DESCRIPTION
146
147 This template engine allows you to use L<Template>::Toolkit in L<Dancer2>.
148
149 =head1 METHODS
150
151 =head2 render($template, \%tokens)
152
153 Renders the template. The first arg is a filename for the template file
154 or a reference to a string that contains the template. The second arg
155 is a hashref for the tokens that you wish to pass to
156 L<Template::Toolkit> for rendering.
157
158 =head1 ADVANCED CUSTOMIZATION
159
160 L<Template>::Toolkit allows you to replace certain parts, like the internal
161 STASH (L<Template::Stash>). In order to do that, one usually passes an object of another
162 implementation such as L<Template::Stash::AutoEscaping> into the constructor.
163
164 Unfortunately that is not possible when you configure L<Template>::Toolkit from
165 your Dancer2 configuration file. You cannot instantiate a Perl object in a yaml file.
166 Instead, you need to subclass this module, and use the subclass in your configuration file.
167
168 A subclass to use the aforementioned L<Template::Stash::AutoEscaping> might look like this:
169
170 package Dancer2::Template::TemplateToolkit::AutoEscaping;
171 # or MyApp::
172
173 use Moo;
174 use Template::Stash::AutoEscaping;
175
176 extends 'Dancer2::Template::TemplateToolkit';
177
178 around '_build_engine' => sub {
179 my $orig = shift;
180 my $self = shift;
181
182 my $tt = $self->$orig(@_);
183
184 # replace the stash object
185 $tt->service->context->{STASH} = Template::Stash::AutoEscaping->new(
186 $self->config->{STASH}
187 );
188
189 return $tt;
190 };
191
192 1;
193
194 You can then use this new subclass in your config file instead of C<template_toolkit>.
195
196 # in config.yml
197 engines:
198 template:
199 TemplateToolkit::AutoEscaping:
200 start_tag: '<%'
201 end_tag: '%>'
202 # optional arguments here
203 STASH:
204
205 The same approach should work for SERVICE (L<Template::Service>), CONTEXT (L<Template::Context>),
206 PARSER (L<Template::Parser>) and GRAMMAR (L<Template::Grammar>). If you intend to replace
207 several of these components in your app, it is suggested to create an app-specific subclass
208 that handles all of them at the same time.
209
210 =head2 Custom Template::Toolkit class
211
212 When subclassing this module it is possible to use a different
213 Template::Toolkit class (for example if you have also subclassed that). To do
214 that simply define a different C<template_class> property:
215
216 package Dancer2::Template::TemplateToolkit::FooBar;
217
218 use Moo;
219
220 extends 'Dancer2::Template::TemplateToolkit';
221
222 has '+template_class' => ( default => 'TemplateFooBar' );
223
224 1;
225
226 =head2 Template Caching
227
228 L<Template>::Tookit templates can be cached by adding the C<COMPILE_EXT> property to your
229 template configuration settings:
230
231 # in config.yml
232 engines:
233 template:
234 template_toolkit:
235 start_tag: '<%'
236 end_tag: '%>'
237 COMPILE_EXT: '.tcc' # cached file extension
238
239 Template caching will avoid the need to re-parse template files or blocks each time they are
240 used. Cached templates are automatically updated when you update the original template file.
241
242 By default, cached templates are saved in the same directory as your template. To save
243 cached templates in a different directory, you can set the C<COMPILE_DIR> property in your
244 Dancer2 configuration file.
245
246 Please see L<Template::Manual::Config/Caching_and_Compiling_Options> for further
247 details and more caching options.
248
249 =head1 SEE ALSO
250
251 L<Dancer2>, L<Dancer2::Core::Role::Template>, L<Template::Toolkit>.
252
253 =head1 AUTHOR
254
255 Dancer Core Developers
256
257 =head1 COPYRIGHT AND LICENSE
258
259 This software is copyright (c) 2026 by Alexis Sukrieh.
260
261 This is free software; you can redistribute it and/or modify it under
262 the same terms as the Perl 5 programming language system itself.
263
264 =cut