SL::{Controller,Presenter}->render: $template kann auch ref auf Instanz von EscapedTe...
[kivitendo-erp.git] / SL / Presenter.pm
1 package SL::Presenter;
2
3 use strict;
4
5 use parent qw(Rose::Object);
6
7 use Carp;
8 use Template;
9
10 use SL::Presenter::CustomerVendor;
11 use SL::Presenter::DeliveryOrder;
12 use SL::Presenter::EscapedText;
13 use SL::Presenter::Invoice;
14 use SL::Presenter::Order;
15 use SL::Presenter::Project;
16 use SL::Presenter::Record;
17
18 sub get {
19   return $::request->presenter;
20 }
21
22 sub render {
23   my $self               = shift;
24   my $template           = shift;
25   my ($options, %locals) = (@_ && ref($_[0])) ? @_ : ({ }, @_);
26
27   # Set defaults for all available options.
28   my %defaults = (
29     type       => 'html',
30     process    => 1,
31   );
32   $options->{$_} //= $defaults{$_} for keys %defaults;
33   $options->{type} = lc $options->{type};
34
35   # Check supplied options for validity.
36   foreach (keys %{ $options }) {
37     croak "Unsupported option: $_" unless $defaults{$_};
38   }
39
40   # Only certain types are supported.
41   croak "Unsupported type: " . $options->{type} unless $options->{type} =~ m/^(?:html|js|json)$/;
42
43   # The "template" argument must be a string or a reference to one.
44   $template = ${ $template }                                       if ((ref($template) || '') eq 'REF') && (ref(${ $template }) eq 'SL::Presenter::EscapedText');
45   croak "Unsupported 'template' reference type: " . ref($template) if ref($template) && (ref($template) !~ m/^(?:SCALAR|SL::Presenter::EscapedText)$/);
46
47   # Look for the file given by $template if $template is not a reference.
48   my $source;
49   if (!ref $template) {
50     $source = "templates/webpages/${template}." . $options->{type};
51     croak "Template file ${source} not found" unless -f $source;
52
53   } elsif (ref($template) eq 'SCALAR') {
54     # Normal scalar reference: hand over to Template
55     $source = $template;
56
57   } else {
58     # Instance of SL::Presenter::EscapedText. Get reference to its content.
59     $source = \$template->{text};
60   }
61
62   # If no processing is requested then return the content.
63   if (!$options->{process}) {
64     # If $template is a reference then don't try to read a file.
65     my $ref = ref $template;
66     return $template                                                                if $ref eq 'SL::Presenter::EscapedText';
67     return SL::Presenter::EscapedText->new(text => ${ $template }, is_escaped => 1) if $ref eq 'SCALAR';
68
69     # Otherwise return the file's content.
70     my $file    = IO::File->new($source, "r") || croak("Template file ${source} could not be read");
71     my $content = do { local $/ = ''; <$file> };
72     $file->close;
73
74     return SL::Presenter::EscapedText->new(text => $content, is_escaped => 1);
75   }
76
77   # Processing was requested. Set up all variables.
78   my %params = ( %locals,
79                  AUTH          => $::auth,
80                  FLASH         => $::form->{FLASH},
81                  FORM          => $::form,
82                  INSTANCE_CONF => $::instance_conf,
83                  LOCALE        => $::locale,
84                  LXCONFIG      => \%::lx_office_conf,
85                  LXDEBUG       => $::lxdebug,
86                  MYCONFIG      => \%::myconfig,
87                  PRESENTER     => $self,
88                );
89
90   my $output;
91   my $parser = $self->get_template;
92   $parser->process($source, \%params, \$output) || croak $parser->error;
93
94   return SL::Presenter::EscapedText->new(text => $output, is_escaped => 1);
95 }
96
97 sub get_template {
98   my ($self) = @_;
99
100   $self->{template} ||=
101     Template->new({ INTERPOLATE  => 0,
102                     EVAL_PERL    => 0,
103                     ABSOLUTE     => 1,
104                     CACHE_SIZE   => 0,
105                     PLUGIN_BASE  => 'SL::Template::Plugin',
106                     INCLUDE_PATH => '.:templates/webpages',
107                     COMPILE_EXT  => '.tcc',
108                     COMPILE_DIR  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
109                     ERROR        => 'templates/webpages/generic/exception.html',
110                   }) || croak;
111
112   return $self->{template};
113 }
114
115 sub escape {
116   my ($self, $text) = @_;
117
118   return SL::Presenter::EscapedText->new(text => $text);
119 }
120
121 sub escaped_text {
122   my ($self, $text) = @_;
123
124   return SL::Presenter::EscapedText->new(text => $text, is_escaped => 1);
125 }
126
127 1;
128
129 __END__
130
131 =head1 NAME
132
133 SL::Presenter - presentation layer class
134
135 =head1 SYNOPSIS
136
137   use SL::Presenter;
138   my $presenter = SL::Presenter->get;
139
140   # Lower-level template parsing:
141   my $html = $presenter->render(
142     'presenter/dir/template.html',
143     var1 => 'value',
144   );
145
146   # Higher-level rendering of certain objects:
147   use SL::DB::Customer;
148
149   my $linked_customer_name = $presenter->customer($customer, display => 'table-cell');
150
151   # Render a list of links to sales/purchase records:
152   use SL::DB::Order;
153
154   my $quotation = SL::DB::Manager::Order->get_first(where => { quotation => 1 });
155   my $records   = $quotation->linked_records(direction => 'to');
156   my $html      = $presenter->grouped_record_list($records);
157
158 =head1 CLASS FUNCTIONS
159
160 =over 4
161
162 =item C<get>
163
164 Returns the global presenter object and creates it if it doesn't exist
165 already.
166
167 =back
168
169 =head1 INSTANCE FUNCTIONS
170
171 =over 4
172
173 =item C<render $template, [ $options, ] %locals>
174
175 Renders the template C<$template>. Provides other variables than
176 C<Form::parse_html_template> does.
177
178 C<$options>, if present, must be a hash reference. All remaining
179 parameters are slurped into C<%locals>.
180
181 This is the backend function that L<SL::Controller::Base/render>
182 calls. The big difference is that the presenter's L<render> function
183 always returns the input and never sends anything to the browser while
184 the controller's function usually sends the result to the
185 controller. Therefore the presenter's L<render> function does not use
186 all of the parameters for controlling the output that the controller's
187 function does.
188
189 What is rendered and how C<$template> is interpreted is determined
190 both by C<$template>'s reference type and by the supplied options.
191
192 If C<$template> is a normal scalar (not a reference) then it is meant
193 to be a template file name relative to the C<templates/webpages>
194 directory. The file name to use is determined by the C<type> option.
195
196 If C<$template> is a reference to a scalar then the referenced
197 scalar's content is used as the content to process. The C<type> option
198 is not considered in this case.
199
200 Other reference types, unknown options and unknown arguments to the
201 C<type> option cause the function to L<croak>.
202
203 The following options are available:
204
205 =over 2
206
207 =item C<type>
208
209 The template type. Can be C<html> (the default), C<js> for JavaScript
210 or C<json> for JSON content. Affects only the extension that's added
211 to the file name given with a non-reference C<$template> argument.
212
213 =item C<process>
214
215 If trueish (which is also the default) it causes the template/content
216 to be processed by the Template toolkit. Otherwise the
217 template/content is returned as-is.
218
219 =back
220
221 If template processing is requested then the template has access to
222 the following variables:
223
224 =over 2
225
226 =item * C<AUTH> -- C<$::auth>
227
228 =item * C<FORM> -- C<$::form>
229
230 =item * C<LOCALE> -- C<$::locale>
231
232 =item * C<LXCONFIG> -- all parameters from C<config/kivitendo.conf>
233 with the same name they appear in the file (first level is the
234 section, second the actual variable, e.g. C<system.dbcharset>,
235 C<features.webdav> etc)
236
237 =item * C<LXDEBUG> -- C<$::lxdebug>
238
239 =item * C<MYCONFIG> -- C<%::myconfig>
240
241 =item * C<SELF> -- the controller instance
242
243 =item * All items from C<%locals>
244
245 =back
246
247 The function will always return the output and never send anything to
248 the browser.
249
250 Example: Render a HTML template with a certain title and a few locals
251
252   $presenter->render('todo/list',
253                      title      => 'List TODO items',
254                      TODO_ITEMS => SL::DB::Manager::Todo->get_all_sorted);
255
256 Example: Render a string and return its content for further processing
257 by the calling function.
258
259   my $content = $presenter->render(\'[% USE JavaScript %][% JavaScript.replace_with("#someid", "js/something") %]');
260
261 Example: Return the content of a JSON template file without processing
262 it at all:
263
264   my $template_content = $presenter->render(
265     'customer/contact',
266     { type => 'json', process => 0 }
267   );
268
269 =item C<escape $text>
270
271 Returns an HTML-escaped version of C<$text>. Instead of a string an
272 instance of the thin proxy-object L<SL::Presenter::EscapedText> is
273 returned.
274
275 It is safe to call C<escape> on an instance of
276 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
277 be returned).
278
279 =item C<escaped_text $text>
280
281 Returns an instance of L<SL::Presenter::EscapedText>. C<$text> is
282 assumed to be a string that has already been HTML-escaped.
283
284 It is safe to call C<escaped_text> on an instance of
285 L<SL::Presenter::EscapedText>. This is a no-op (the same instance will
286 be returned).
287
288 =item C<get_template>
289
290 Returns the global instance of L<Template> and creates it if it
291 doesn't exist already.
292
293 =back
294
295 =head1 AUTHOR
296
297 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
298
299 =cut