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