options_for_select - subs übergeben
[kivitendo-erp.git] / SL / Template / Plugin / L.pm
1 package SL::Template::Plugin::L;
2
3 use base qw( Template::Plugin );
4 use Template::Plugin;
5 use List::MoreUtils qw(apply);
6
7 use strict;
8
9 { # This will give you an id for identifying html tags and such.
10   # It's guaranteed to be unique unless you exceed 10 mio calls per request.
11   # Do not use these id's to store information across requests.
12 my $_id_sequence = int rand 1e7;
13 sub _tag_id {
14   return $_id_sequence = ($_id_sequence + 1) % 1e7;
15 }
16 }
17
18 sub _H {
19   my $string = shift;
20   return $::locale->quote_special_chars('HTML', $string);
21 }
22
23 sub _hashify {
24   return (@_ && (ref($_[0]) eq 'HASH')) ? %{ $_[0] } : @_;
25 }
26
27 sub new {
28   my $class   = shift;
29   my $context = shift;
30
31   return bless { }, $class;
32 }
33
34 sub name_to_id {
35   my $self =  shift;
36   my $name =  shift;
37
38   $name    =~ s/[^\w_]/_/g;
39   $name    =~ s/_+/_/g;
40
41   return $name;
42 }
43
44 sub attributes {
45   my $self    = shift;
46   my %options = _hashify(@_);
47
48   my @result = ();
49   while (my ($name, $value) = each %options) {
50     next unless $name;
51     $value ||= '';
52     push @result, _H($name) . '="' . _H($value) . '"';
53   }
54
55   return @result ? ' ' . join(' ', @result) : '';
56 }
57
58 sub html_tag {
59   my $self       = shift;
60   my $tag        = shift;
61   my $content    = shift;
62   my $attributes = $self->attributes(@_);
63
64   return "<${tag}${attributes}/>" unless defined($content);
65   return "<${tag}${attributes}>${content}</${tag}>";
66 }
67
68 sub select_tag {
69   my $self            = shift;
70   my $name            = shift;
71   my $options_str     = shift;
72   my %attributes      = _hashify(@_);
73
74   $attributes{id}   ||= $self->name_to_id($name);
75   $options_str        = $self->options_for_select($options_str) if ref $options_str;
76
77   return $self->html_tag('select', $options_str, %attributes, name => $name);
78 }
79
80 sub textarea_tag {
81   my $self            = shift;
82   my $name            = shift;
83   my $content         = shift;
84   my %attributes      = _hashify(@_);
85
86   $attributes{id}   ||= $self->name_to_id($name);
87   $content            = $content ? '' : _H($content);
88
89   return $self->html_tag('textarea', $content, %attributes, name => $name);
90 }
91
92 sub checkbox_tag {
93   my $self             = shift;
94   my $name             = shift;
95   my %attributes       = _hashify(@_);
96
97   $attributes{id}    ||= $self->name_to_id($name);
98   $attributes{value}   = 1 unless defined $attributes{value};
99   my $label            = delete $attributes{label};
100
101   if ($attributes{checked}) {
102     $attributes{checked} = 'checked';
103   } else {
104     delete $attributes{checked};
105   }
106
107   my $code  = $self->html_tag('input', undef,  %attributes, name => $name, type => 'checkbox');
108   $code    .= $self->html_tag('label', $label, for => $attributes{id}) if $label;
109
110   return $code;
111 }
112
113 sub radio_button_tag {
114   my $self             = shift;
115   my $name             = shift;
116   my %attributes       = _hashify(@_);
117
118   $attributes{value}   = 1 unless defined $attributes{value};
119   $attributes{id}    ||= $self->name_to_id($name . "_" . $attributes{value});
120   my $label            = delete $attributes{label};
121
122   if ($attributes{checked}) {
123     $attributes{checked} = 'checked';
124   } else {
125     delete $attributes{checked};
126   }
127
128   my $code  = $self->html_tag('input', undef,  %attributes, name => $name, type => 'radio');
129   $code    .= $self->html_tag('label', $label, for => $attributes{id}) if $label;
130
131   return $code;
132 }
133
134 sub input_tag {
135   my $self            = shift;
136   my $name            = shift;
137   my $value           = shift;
138   my %attributes      = _hashify(@_);
139
140   $attributes{id}   ||= $self->name_to_id($name);
141   $attributes{type} ||= 'text';
142
143   return $self->html_tag('input', undef, %attributes, name => $name, value => $value);
144 }
145
146 sub hidden_tag {
147   return shift->input_tag(@_, type => 'hidden');
148 }
149
150 sub submit_tag {
151   return shift->input_tag(@_, type => 'submit', class => 'submit');
152 }
153
154 sub options_for_select {
155   my $self            = shift;
156   my $collection      = shift;
157   my %options         = _hashify(@_);
158
159   my $value_key       = $options{value} || 'id';
160   my $title_key       = $options{title} || $value_key;
161
162   my $value_sub       = $options{value_sub};
163   my $title_sub       = $options{title_sub};
164
165   my $value_title_sub = $options{value_title_sub};
166
167   my $access = sub {
168     my ($element, $index, $key, $sub) = @_;
169     my $ref = ref $element;
170     return  $sub            ? $sub->($element)
171          : !$ref            ? $element
172          :  $ref eq 'ARRAY' ? $element->[$index]
173          :  $ref eq 'HASH'  ? $element->{$key}
174          :                    $element->$key;
175   };
176
177   my @elements = ();
178   push @elements, [ undef, $options{empty_title} || '' ] if $options{with_empty};
179   push @elements, map [
180     $value_title_sub ? $value_title_sub->($_) : (
181       $access->($_, 0, $value_key, $value_sub),
182       $access->($_, 1, $title_key, $title_sub),
183     )
184   ], @{ $collection } if $collection && ref $collection eq 'ARRAY';
185
186   my $code = '';
187   foreach my $result (@elements) {
188     my %attributes = ( value => $result->[0] );
189     $attributes{selected} = 'selected' if $options{default} && ($options{default} eq ($result->[0] || ''));
190
191     $code .= $self->html_tag('option', _H($result->[1]), %attributes);
192   }
193
194   return $code;
195 }
196
197 sub javascript {
198   my ($self, $data) = @_;
199   return $self->html_tag('script', $data, type => 'text/javascript');
200 }
201
202 sub date_tag {
203   my ($self, $name, $value, @slurp) = @_;
204   my %params   = _hashify(@slurp);
205   my $name_e   = _H($name);
206   my $seq      = _tag_id();
207   my $datefmt  = apply {
208     s/d+/\%d/gi;
209     s/m+/\%m/gi;
210     s/y+/\%Y/gi;
211   } $::myconfig{"dateformat"};
212
213   $params{cal_align} ||= 'BR';
214
215   $self->input_tag($name, $value,
216     id     => $name_e,
217     size   => 11,
218     title  => _H($::myconfig{dateformat}),
219     onBlur => 'check_right_date_format(this)',
220     %params,
221   ) . ((!$params{no_cal}) ?
222   $self->html_tag('img', undef,
223     src    => 'image/calendar.png',
224     id     => "trigger$seq",
225     title  => _H($::myconfig{dateformat}),
226     %params,
227   ) .
228   $self->javascript(
229     "Calendar.setup({ inputField: '$name_e', ifFormat: '$datefmt', align: '$params{cal_align}', button: 'trigger$seq'  });"
230   ) : '');
231
232 sub javascript_tag {
233   my $self = shift;
234   my $code = '';
235
236   foreach my $file (@_) {
237     $file .= '.js'        unless $file =~ m/\.js$/;
238     $file  = "js/${file}" unless $file =~ m|/|;
239
240     $code .= qq|<script type="text/javascript" src="${file}"></script>|;
241   }
242
243   return $code;
244 }
245
246 1;
247
248 __END__
249
250 =head1 NAME
251
252 SL::Templates::Plugin::L -- Layouting / tag generation
253
254 =head1 SYNOPSIS
255
256 Usage from a template:
257
258   [% USE L %]
259
260   [% L.select_tag('direction', [ [ 'left', 'To the left' ], [ 'right', 'To the right' ] ]) %]
261
262   [% L.select_tag('direction', L.options_for_select([ { direction => 'left',  display => 'To the left'  },
263                                                       { direction => 'right', display => 'To the right' } ],
264                                                     value => 'direction', title => 'display', default => 'right')) %]
265
266 =head1 DESCRIPTION
267
268 A module modeled a bit after Rails' ActionView helpers. Several small
269 functions that create HTML tags from various kinds of data sources.
270
271 =head1 FUNCTIONS
272
273 =head2 LOW-LEVEL FUNCTIONS
274
275 =over 4
276
277 =item C<name_to_id $name>
278
279 Converts a name to a HTML id by replacing various characters.
280
281 =item C<attributes %items>
282
283 Creates a string from all elements in C<%items> suitable for usage as
284 HTML tag attributes. Keys and values are HTML escaped even though keys
285 must not contain non-ASCII characters for browsers to accept them.
286
287 =item C<html_tag $tag_name, $content_string, %attributes>
288
289 Creates an opening and closing HTML tag for C<$tag_name> and puts
290 C<$content_string> between the two. If C<$content_string> is undefined
291 or empty then only a E<lt>tag/E<gt> tag will be created. Attributes
292 are key/value pairs added to the opening tag.
293
294 C<$content_string> is not HTML escaped.
295
296 =back
297
298 =head2 HIGH-LEVEL FUNCTIONS
299
300 =over 4
301
302 =item C<select_tag $name, $options_string, %attributes>
303
304 Creates a HTML 'select' tag named C<$name> with the contents
305 C<$options_string> and with arbitrary HTML attributes from
306 C<%attributes>. The tag's C<id> defaults to C<name_to_id($name)>.
307
308 The C<$options_string> is usually created by the
309 L</options_for_select> function. If C<$options_string> is an array
310 reference then it will be passed to L</options_for_select>
311 automatically.
312
313 =item C<input_tag $name, $value, %attributes>
314
315 Creates a HTML 'input type=text' tag named C<$name> with the value
316 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
317 tag's C<id> defaults to C<name_to_id($name)>.
318
319 =item C<hidden_tag $name, $value, %attributes>
320
321 Creates a HTML 'input type=hidden' tag named C<$name> with the value
322 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
323 tag's C<id> defaults to C<name_to_id($name)>.
324
325 =item C<submit_tag $name, $value, %attributes>
326
327 Creates a HTML 'input type=submit class=submit' tag named C<$name> with the
328 value C<$value> and with arbitrary HTML attributes from C<%attributes>. The
329 tag's C<id> defaults to C<name_to_id($name)>.
330
331 =item C<textarea_tag $name, $value, %attributes>
332
333 Creates a HTML 'textarea' tag named C<$name> with the content
334 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
335 tag's C<id> defaults to C<name_to_id($name)>.
336
337 =item C<checkbox_tag $name, %attributes>
338
339 Creates a HTML 'input type=checkbox' tag named C<$name> with arbitrary
340 HTML attributes from C<%attributes>. The tag's C<id> defaults to
341 C<name_to_id($name)>. The tag's C<value> defaults to C<1>.
342
343 If C<%attributes> contains a key C<label> then a HTML 'label' tag is
344 created with said C<label>. No attribute named C<label> is created in
345 that case.
346
347 =item C<date_tag $name, $value, cal_align =E<gt> $align_code, %attributes>
348
349 Creates a date input field, with an attached javascript that will open a
350 calendar on click. The javascript ist by default anchoered at the bottom right
351 sight. This can be overridden with C<cal_align>, see Calendar documentation for
352 the details, usually you'll want a two letter abbreviation of the alignment.
353 Right + Bottom becomes C<BL>.
354
355 =item C<radio_button_tag $name, %attributes>
356
357 Creates a HTML 'input type=radio' tag named C<$name> with arbitrary
358 HTML attributes from C<%attributes>. The tag's C<value> defaults to
359 C<1>. The tag's C<id> defaults to C<name_to_id($name . "_" . $value)>.
360
361 If C<%attributes> contains a key C<label> then a HTML 'label' tag is
362 created with said C<label>. No attribute named C<label> is created in
363 that case.
364
365 =item C<javascript_tag $file1, $file2, $file3...>
366
367 Creates a HTML 'E<lt>script type="text/javascript" src="..."E<gt>'
368 tag for each file name parameter passed. Each file name will be
369 postfixed with '.js' if it isn't already and prefixed with 'js/' if it
370 doesn't contain a slash.
371
372 =back
373
374 =head2 CONVERSION FUNCTIONS
375
376 =over 4
377
378 =item C<options_for_select \@collection, %options>
379
380 Creates a string suitable for a HTML 'select' tag consisting of one
381 'E<lt>optionE<gt>' tag for each element in C<\@collection>. The value
382 to use and the title to display are extracted from the elements in
383 C<\@collection>. Each element can be one of four things:
384
385 =over 12
386
387 =item 1. An array reference with at least two elements. The first element is
388 the value, the second element is its title.
389
390 =item 2. A scalar. The scalar is both the value and the title.
391
392 =item 3. A hash reference. In this case C<%options> must contain
393 I<value> and I<title> keys that name the keys in the element to use
394 for the value and title respectively.
395
396 =item 4. A blessed reference. In this case C<%options> must contain
397 I<value> and I<title> keys that name functions called on the blessed
398 reference whose return values are used as the value and title
399 respectively.
400
401 =back
402
403 For cases 3 and 4 C<$options{value}> defaults to C<id> and
404 C<$options{title}> defaults to C<$options{value}>.
405
406 In addition to pure keys/method you can also provide coderefs as I<value_sub>
407 and/or I<title_sub>. If present, these take precedence over keys or methods,
408 and are called with the element as first argument. It must return the value or
409 title.
410
411 Lastly a joint coderef I<value_title_sub> may be provided, which in turn takes
412 precedence over each individual sub. It will only be called once for each
413 element and must return a list of value and title.
414
415 If the option C<with_empty> is set then an empty element (value
416 C<undef>) will be used as the first element. The title to display for
417 this element can be set with the option C<empty_title> and defaults to
418 an empty string.
419
420 =back
421
422 =head1 MODULE AUTHORS
423
424 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
425
426 L<http://linet-services.de>