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