implement defmap
[html-element-library.git] / lib / HTML / Element / Library.pm
CommitLineData
67e78ff2 1package HTML::Element::Library;
2
3use 5.006001;
4use strict;
5use warnings;
6
7
8our $DEBUG = 0;
9#our $DEBUG = 1;
10
11use Array::Group qw(:all);
12use Carp qw(confess);
13use Data::Dumper;
14use HTML::Element;
3dad7198 15use List::Util qw(first);
67e78ff2 16use List::MoreUtils qw/:all/;
17use Params::Validate qw(:all);
18use Scalar::Listify;
19#use Tie::Cycle;
20use List::Rotation::Cycle;
21
22our %EXPORT_TAGS = ( 'all' => [ qw() ] );
23our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
24our @EXPORT = qw();
25
26
27
de64e3d9 28our $VERSION = '3.53';
67e78ff2 29
30
31# Preloaded methods go here.
32
33sub HTML::Element::siblings {
34 my $element = shift;
35 my $p = $element->parent;
36 return () unless $p;
37 $p->content_list;
38}
39
f25dca7f
TB
40sub HTML::Element::defmap {
41 my($tree,$attr,$hashref)=@_;
42
43 while (my ($k, $v) = (each %$hashref)) {
44 my $found = $tree->look_down($attr => $k);
45 if ($found) {
46 $found->replace_content( $v );
47 }
48 }
49
50}
51
52
9b7a5679
TB
53sub HTML::Element::hash_map {
54 my $container = shift;
55
56 my %p = validate(@_, {
57 hash => { type => HASHREF },
58 to_attr => 1,
d9f4bd5a 59 excluding => { type => ARRAYREF , default => [] },
9b7a5679
TB
60 debug => { default => 0 },
61 });
62
d9f4bd5a
TB
63 warn 'The container tag is ', $container->tag if $p{debug} ;
64 warn 'hash' . Dumper($p{hash}) if $p{debug} ;
f25dca7f 65 warn 'at_under' . Dumper(\@_) if $p{debug} ;
d9f4bd5a
TB
66
67 my @same_as = $container->look_down( $p{to_attr} => qr/.+/ ) ;
68
69 warn 'Found ' . scalar(@same_as) . ' nodes' if $p{debug} ;
70
9b7a5679
TB
71
72 for my $same_as (@same_as) {
d9f4bd5a
TB
73 my $attr_val = $same_as->attr($p{to_attr}) ;
74 if (first { $attr_val eq $_ } @{$p{excluding}}) {
75 warn "excluding $attr_val" if $p{debug} ;
76 next;
77 }
78 warn "processing $attr_val" if $p{debug} ;
79 $same_as->replace_content( $p{hash}->{$attr_val} ) ;
9b7a5679 80 }
3dad7198
TB
81
82}
83
f25dca7f
TB
84sub HTML::Element::hashmap {
85 my ($container, $attr_name, $hashref, $excluding, $debug) = @_;
86
87 $excluding ||= [] ;
88
89 $container->hash_map(hash => $hashref,
90 to_attr => $attr_name,
91 excluding => $excluding,
92 debug => $debug);
93
94}
95
3dad7198 96
de64e3d9 97sub HTML::Element::passover {
98 my ($tree, $child_id) = @_;
99
3dad7198
TB
100 warn "ARGS: my ($tree, $child_id)" if $DEBUG;
101 warn $tree->as_HTML(undef, ' ') if $DEBUG;
de64e3d9 102
103 my $exodus = $tree->look_down(id => $child_id);
104
3dad7198
TB
105 warn "E: $exodus" if $DEBUG;
106
de64e3d9 107 my @s = HTML::Element::siblings($exodus);
108
de64e3d9 109 for my $s (@s) {
de64e3d9 110 next unless ref $s;
111 if ($s->attr('id') eq $child_id) {
112 ;
113 } else {
114 $s->delete;
115 }
116 }
117
118 return $exodus; # Goodbye Egypt! http://en.wikipedia.org/wiki/Passover
119
120}
121
67e78ff2 122sub HTML::Element::sibdex {
123
124 my $element = shift;
125 firstidx { $_ eq $element } $element->siblings
126
127}
128
129sub HTML::Element::addr { goto &HTML::Element::sibdex }
130
131sub HTML::Element::replace_content {
132 my $elem = shift;
133 $elem->delete_content;
134 $elem->push_content(@_);
135}
136
137sub HTML::Element::wrap_content {
138 my($self, $wrap) = @_;
139 my $content = $self->content;
140 if (ref $content) {
141 $wrap->push_content(@$content);
142 @$content = ($wrap);
143 }
144 else {
145 $self->push_content($wrap);
146 }
147 $wrap;
148}
149
150sub HTML::Element::Library::super_literal {
151 my($text) = @_;
152
153 HTML::Element->new('~literal', text => $text);
154}
155
156
157sub HTML::Element::position {
158 # Report coordinates by chasing addr's up the
159 # HTML::ElementSuper tree. We know we've reached
160 # the top when a) there is no parent, or b) the
161 # parent is some HTML::Element unable to report
162 # it's position.
163 my $p = shift;
164 my @pos;
165 while ($p) {
166 my $a = $p->addr;
167 unshift(@pos, $a) if defined $a;
168 $p = $p->parent;
169 }
170 @pos;
171}
172
173
174sub HTML::Element::content_handler {
3c14ea1e 175 my ($tree, %content_hash) = @_;
176
177 for my $k (keys %content_hash) {
178 $tree->set_child_content(id => $k, $content_hash{$k});
179 }
67e78ff2 180
67e78ff2 181
182}
183
184
185sub make_counter {
186 my $i = 1;
187 sub {
188 shift() . ':' . $i++
189 }
190}
191
192
193sub HTML::Element::iter {
194 my ($tree, $p, @data) = @_;
195
196 # warn 'P: ' , $p->attr('id') ;
197 # warn 'H: ' , $p->as_HTML;
198
199 # my $id_incr = make_counter;
200 my @item = map {
201 my $new_item = clone $p;
202 $new_item->replace_content($_);
203 # $new_item->attr('id', $id_incr->( $p->attr('id') ));
204 $new_item;
205 } @data;
206
207 $p->replace_with(@item);
208
209}
210
211
212sub HTML::Element::iter2 {
213
214 my $tree = shift;
215
216 #warn "INPUT TO TABLE2: ", Dumper \@_;
217
218 my %p = validate(
219 @_, {
220 wrapper_ld => { default => ['_tag' => 'dl'] },
221 wrapper_data => 1,
222 wrapper_proc => { default => undef },
223 item_ld => { default => sub {
224 my $tree = shift;
225 [
226 $tree->look_down('_tag' => 'dt'),
227 $tree->look_down('_tag' => 'dd')
228 ];
229 }
230 },
231 item_data => { default => sub { my ($wrapper_data) = @_;
232 shift(@{$wrapper_data}) ;
233 }},
234 item_proc => {
235 default => sub {
236 my ($item_elems, $item_data, $row_count) = @_;
237 $item_elems->[$_]->replace_content($item_data->[$_]) for (0,1) ;
238 $item_elems;
239 }},
240 splice => { default => sub {
241 my ($container, @item_elems) = @_;
242 $container->splice_content(0, 2, @item_elems);
243 }
244 },
245 debug => {default => 0}
246 }
247 );
248
249 warn "wrapper_data: " . Dumper $p{wrapper_data} if $p{debug} ;
250
251 my $container = ref_or_ld($tree, $p{wrapper_ld});
3dad7198 252 warn "container: " . $container if $p{debug} ;
67e78ff2 253 warn "wrapper_(preproc): " . $container->as_HTML if $p{debug} ;
254 $p{wrapper_proc}->($container) if defined $p{wrapper_proc} ;
255 warn "wrapper_(postproc): " . $container->as_HTML if $p{debug} ;
256
257 my $_item_elems = $p{item_ld}->($container);
258
259
260
261 my $row_count;
262 my @item_elem;
263 {
264 my $item_data = $p{item_data}->($p{wrapper_data});
265 last unless defined $item_data;
266
267 warn Dumper("item_data", $item_data);
268
269
270 my $item_elems = [ map { $_->clone } @{$_item_elems} ] ;
271
272 if ($p{debug}) {
273 for (@{$item_elems}) {
274 warn "ITEM_ELEMS ", $_->as_HTML;
275 }
276 }
277
278 my $new_item_elems = $p{item_proc}->($item_elems, $item_data, ++$row_count);
279
280 if ($p{debug}) {
281 for (@{$new_item_elems}) {
282 warn "NEWITEM_ELEMS ", $_->as_HTML;
283 }
284 }
285
286
287 push @item_elem, @{$new_item_elems} ;
288
289 redo;
290 }
291
292 warn "pushing " . @item_elem . " elems " if $p{debug} ;
293
294 $p{splice}->($container, @item_elem);
295
296}
297
298sub HTML::Element::dual_iter {
299 my ($parent, $data) = @_;
300
301 my ($prototype_a, $prototype_b) = $parent->content_list;
302
303 # my $id_incr = make_counter;
304
305 my $i;
306
307 @$data %2 == 0 or
308 confess 'dataset does not contain an even number of members';
309
310 my @iterable_data = ngroup 2 => @$data;
311
312 my @item = map {
313 my ($new_a, $new_b) = map { clone $_ } ($prototype_a, $prototype_b) ;
314 $new_a->splice_content(0,1, $_->[0]);
315 $new_b->splice_content(0,1, $_->[1]);
316 #$_->attr('id', $id_incr->($_->attr('id'))) for ($new_a, $new_b) ;
317 ($new_a, $new_b)
318 } @iterable_data;
319
320 $parent->splice_content(0, 2, @item);
321
322}
323
324
325sub HTML::Element::set_child_content {
326 my $tree = shift;
327 my $content = pop;
328 my @look_down = @_;
329
330 my $content_tag = $tree->look_down(@look_down);
331
332 unless ($content_tag) {
333 warn "criteria [@look_down] not found";
334 return;
335 }
336
337 $content_tag->replace_content($content);
338
339}
340
341sub HTML::Element::highlander {
342 my ($tree, $local_root_id, $aref, @arg) = @_;
343
344 ref $aref eq 'ARRAY' or confess
345 "must supply array reference";
346
347 my @aref = @$aref;
348 @aref % 2 == 0 or confess
349 "supplied array ref must have an even number of entries";
350
351 warn __PACKAGE__ if $DEBUG;
352
353 my $survivor;
354 while (my ($id, $test) = splice @aref, 0, 2) {
355 warn $id if $DEBUG;
356 if ($test->(@arg)) {
357 $survivor = $id;
358 last;
359 }
360 }
361
362
363 my @id_survivor = (id => $survivor);
364 my $survivor_node = $tree->look_down(@id_survivor);
365# warn $survivor;
366# warn $local_root_id;
367# warn $node;
368
369 warn "survivor: $survivor" if $DEBUG;
370 warn "tree: " . $tree->as_HTML if $DEBUG;
371
372 $survivor_node or die "search for @id_survivor failed in tree($tree): " . $tree->as_HTML;
373
374 my $survivor_node_parent = $survivor_node->parent;
375 $survivor_node = $survivor_node->clone;
376 $survivor_node_parent->replace_content($survivor_node);
377
378 warn "new tree: " . $tree->as_HTML if $DEBUG;
379
380 $survivor_node;
381}
382
383
384sub HTML::Element::highlander2 {
385 my $tree = shift;
386
387 my %p = validate(@_, {
388 cond => { type => ARRAYREF },
389 cond_arg => { type => ARRAYREF,
390 default => []
391 },
392 debug => { default => 0 }
393 }
394 );
395
396
397 my @cond = @{$p{cond}};
398 @cond % 2 == 0 or confess
399 "supplied array ref must have an even number of entries";
400
401 warn __PACKAGE__ if $p{debug};
402
403 my @cond_arg = @{$p{cond_arg}};
404
405 my $survivor; my $then;
406 while (my ($id, $if_then) = splice @cond, 0, 2) {
407
408 warn $id if $p{debug};
409 my ($if, $_then);
410
411 if (ref $if_then eq 'ARRAY') {
412 ($if, $_then) = @$if_then;
413 } else {
414 ($if, $_then) = ($if_then, sub {});
415 }
416
417 if ($if->(@cond_arg)) {
418 $survivor = $id;
419 $then = $_then;
420 last;
421 }
422
423 }
424
425 my @ld = (ref $survivor eq 'ARRAY')
426 ? @$survivor
427 : (id => $survivor)
428 ;
429
430 warn "survivor: ", $survivor if $p{debug};
431 warn "survivor_ld: ", Dumper \@ld if $p{debug};
432
433
434 my $survivor_node = $tree->look_down(@ld);
435
436 $survivor_node or confess
437 "search for @ld failed in tree($tree): " . $tree->as_HTML;
438
439 my $survivor_node_parent = $survivor_node->parent;
440 $survivor_node = $survivor_node->clone;
441 $survivor_node_parent->replace_content($survivor_node);
442
443
444 # **************** NEW FUNCTIONALITY *******************
445
446 # apply transforms on survivor node
447
448
449 warn "SURV::pre_trans " . $survivor_node->as_HTML if $p{debug};
450 $then->($survivor_node, @cond_arg);
451 warn "SURV::post_trans " . $survivor_node->as_HTML if $p{debug};
452
453 # **************** NEW FUNCTIONALITY *******************
454
455
456
457
458 $survivor_node;
459}
460
461
462sub overwrite_action {
463 my ($mute_node, %X) = @_;
464
465 $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
466}
467
468
469sub HTML::Element::overwrite_attr {
470 my $tree = shift;
471
472 $tree->mute_elem(@_, \&overwrite_action);
473}
474
475
476
477sub HTML::Element::mute_elem {
478 my ($tree, $mute_attr, $closures, $post_hook) = @_;
479
480 warn "my mute_node = $tree->look_down($mute_attr => qr/.*/) ;";
481 my @mute_node = $tree->look_down($mute_attr => qr/.*/) ;
482
483 for my $mute_node (@mute_node) {
484 my ($local_attr,$mute_key) = split /\s+/, $mute_node->attr($mute_attr);
485 my $local_attr_value_current = $mute_node->attr($local_attr);
486 my $local_attr_value_new = $closures->{$mute_key}->($tree, $mute_node, $local_attr_value_current);
487 $post_hook->(
488 $mute_node,
489 tree => $tree,
490 local_attr => {
491 name => $local_attr,
492 value => {
493 current => $local_attr_value_current,
494 new => $local_attr_value_new
495 }
496 }
497 ) if ($post_hook) ;
498 }
499}
500
501
502
503sub HTML::Element::table {
504
505 my ($s, %table) = @_;
506
507 my $table = {};
508
509 # use Data::Dumper; warn Dumper \%table;
510
511 # ++$DEBUG if $table{debug} ;
512
513
514 # Get the table element
515 $table->{table_node} = $s->look_down(id => $table{gi_table});
516 $table->{table_node} or confess
517 "table tag not found via (id => $table{gi_table}";
518
519 # Get the prototype tr element(s)
520 my @table_gi_tr = listify $table{gi_tr} ;
521 my @iter_node = map
522 {
523 my $tr = $table->{table_node}->look_down(id => $_);
524 $tr or confess "tr with id => $_ not found";
525 $tr;
526 } @table_gi_tr;
527
528 warn "found " . @iter_node . " iter nodes " if $DEBUG;
529 # tie my $iter_node, 'Tie::Cycle', \@iter_node;
530 my $iter_node = List::Rotation::Cycle->new(@iter_node);
531
532 # warn $iter_node;
533 warn Dumper ($iter_node, \@iter_node) if $DEBUG;
534
535 # $table->{content} = $table{content};
536 #$table->{parent} = $table->{table_node}->parent;
537
538
539 # $table->{table_node}->detach;
540 # $_->detach for @iter_node;
541
542 my @table_rows;
543
544 {
545 my $row = $table{tr_data}->($table, $table{table_data});
546 last unless defined $row;
547
548 # get a sample table row and clone it.
549 my $I = $iter_node->next;
550 warn "I: $I" if $DEBUG;
551 my $new_iter_node = $I->clone;
552
553
554 $table{td_data}->($new_iter_node, $row);
555 push @table_rows, $new_iter_node;
556
557 redo;
558 }
559
560 if (@table_rows) {
561
562 my $replace_with_elem = $s->look_down(id => shift @table_gi_tr) ;
563 for (@table_gi_tr) {
564 $s->look_down(id => $_)->detach;
565 }
566
567 $replace_with_elem->replace_with(@table_rows);
568
569 }
570
571}
572
573sub ref_or_ld {
574
575 my ($tree, $slot) = @_;
576
577 if (ref($slot) eq 'CODE') {
578 $slot->($tree);
579 } else {
580 $tree->look_down(@$slot);
581 }
582}
583
584
585
586sub HTML::Element::table2 {
587
588 my $tree = shift;
589
590
591
592 my %p = validate(
593 @_, {
594 table_ld => { default => ['_tag' => 'table'] },
595 table_data => 1,
596 table_proc => { default => undef },
597
598 tr_ld => { default => ['_tag' => 'tr'] },
599 tr_data => { default => sub { my ($self, $data) = @_;
600 shift(@{$data}) ;
601 }},
602 tr_base_id => { default => undef },
603 tr_proc => { default => sub {} },
604 td_proc => 1,
605 debug => {default => 0}
606 }
607 );
608
609 warn "INPUT TO TABLE2: ", Dumper \@_ if $p{debug};
610
611 warn "table_data: " . Dumper $p{table_data} if $p{debug} ;
612
613 my $table = {};
614
615 # use Data::Dumper; warn Dumper \%table;
616
617 # ++$DEBUG if $table{debug} ;
618
619 # Get the table element
5f53bf21 620 #warn 1;
67e78ff2 621 $table->{table_node} = ref_or_ld( $tree, $p{table_ld} ) ;
5f53bf21 622 #warn 2;
67e78ff2 623 $table->{table_node} or confess
624 "table tag not found via " . Dumper($p{table_ld}) ;
625
626 warn "table: " . $table->{table_node}->as_HTML if $p{debug};
627
628
629 # Get the prototype tr element(s)
630 my @proto_tr = ref_or_ld( $table->{table_node}, $p{tr_ld} ) ;
631
632 warn "found " . @proto_tr . " iter nodes " if $p{debug};
633
634 @proto_tr or return ;
635
636 if ($p{debug}) {
637 warn $_->as_HTML for @proto_tr;
638 }
639 my $proto_tr = List::Rotation::Cycle->new(@proto_tr);
640
641 my $tr_parent = $proto_tr[0]->parent;
642 warn "parent element of trs: " . $tr_parent->as_HTML if $p{debug};
643
644 my $row_count;
645
646 my @table_rows;
647
648 {
649 my $row = $p{tr_data}->($table, $p{table_data}, $row_count);
650 warn "data row: " . Dumper $row if $p{debug};
651 last unless defined $row;
652
653 # wont work: my $new_iter_node = $table->{iter_node}->clone;
654 my $new_tr_node = $proto_tr->next->clone;
655 warn "new_tr_node: $new_tr_node" if $p{debug};
656
657 $p{tr_proc}->($tree, $new_tr_node, $row, $p{tr_base_id}, ++$row_count)
658 if defined $p{tr_proc};
659
660 warn "data row redux: " . Dumper $row if $p{debug};
5f53bf21 661 #warn 3.3;
67e78ff2 662
663 $p{td_proc}->($new_tr_node, $row);
664 push @table_rows, $new_tr_node;
665
5f53bf21 666 #warn 4.4;
67e78ff2 667
668 redo;
669 }
670
671 $_->detach for @proto_tr;
672
673 $tr_parent->push_content(@table_rows) if (@table_rows) ;
674
675}
676
677
678sub HTML::Element::unroll_select {
679
680 my ($s, %select) = @_;
681
682 my $select = {};
683
f25dca7f
TB
684 warn "Select Hash: " . Dumper(\%select) if $select{debug};
685
67e78ff2 686 my $select_node = $s->look_down(id => $select{select_label});
3caedb5b 687 warn "Select Node: " . $select_node if $select{debug};
67e78ff2 688
3caedb5b
TB
689 unless ($select{append}) {
690 for my $option ($select_node->look_down('_tag' => 'option')) {
691 $option->delete;
692 }
693 }
67e78ff2 694
67e78ff2 695
3caedb5b
TB
696 my $option = HTML::Element->new('option');
697 warn "Option Node: " . $option if $select{debug};
67e78ff2 698
699 $option->detach;
700
701 while (my $row = $select{data_iter}->($select{data}))
702 {
3caedb5b
TB
703 warn "Data Row:" . Dumper($row) if $select{debug};
704 my $o = $option->clone;
705 $o->attr('value', $select{option_value}->($row));
706 $o->attr('SELECTED', 1) if (exists $select{option_selected} and $select{option_selected}->($row)) ;
707
708 $o->replace_content($select{option_content}->($row));
709 $select_node->push_content($o);
710 warn $o->as_HTML if $select{debug};
67e78ff2 711 }
712
713
714}
715
716
717
718sub HTML::Element::set_sibling_content {
719 my ($elt, $content) = @_;
720
721 $elt->parent->splice_content($elt->pindex + 1, 1, $content);
722
723}
724
725sub HTML::TreeBuilder::parse_string {
726 my ($package, $string) = @_;
727
728 my $h = HTML::TreeBuilder->new;
729 HTML::TreeBuilder->parse($string);
730
731}
732
733
734
7351;
736__END__
737# Below is stub documentation for your module. You'd better edit it!
738
739=head1 NAME
740
741HTML::Element::Library - HTML::Element convenience functions
742
743=head1 SYNOPSIS
744
745 use HTML::Element::Library;
746 use HTML::TreeBuilder;
747
748=head1 DESCRIPTION
749
750This method provides API calls for common actions on trees when using
751L<HTML::Tree>.
752
753=head1 METHODS
754
755The test suite contains examples of each of these methods in a
756file C<t/$method.t>
757
758=head2 Positional Querying Methods
759
760=head3 $elem->siblings
761
762Return a list of all nodes under the same parent.
763
764=head3 $elem->sibdex
765
766Return the index of C<$elem> into the array of siblings of which it is
767a part. L<HTML::ElementSuper> calls this method C<addr> but I don't think
768that is a descriptive name. And such naming is deceptively close to the
769C<address> function of C<HTML::Element>. HOWEVER, in the interest of
770backwards compatibility, both methods are available.
771
772=head3 $elem->addr
773
774Same as sibdex
775
776=head3 $elem->position()
777
778Returns the coordinates of this element in the tree it inhabits.
779This is accomplished by succesively calling addr() on ancestor
780elements until either a) an element that does not support these
781methods is found, or b) there are no more parents. The resulting
782list is the n-dimensional coordinates of the element in the tree.
783
784=head2 Element Decoration Methods
785
786=head3 HTML::Element::Library::super_literal($text)
787
788In L<HTML::Element>, Sean Burke discusses super-literals. They are
789text which does not get escaped. Great for includng Javascript in
790HTML. Also great for including foreign language into a document.
791
792So, you basically toss C<super_literal> your text and back comes
793your text wrapped in a C<~literal> element.
794
795One of these days, I'll around to writing a nice C<EXPORT> section.
796
797=head2 Tree Rewriting Methods
798
f25dca7f 799=head3 $elem->hashmap($attr_name, \%hashref, \@excluded, $debug)
9b7a5679
TB
800
801This method is designed to take a hashref and populate a series of elements. For example:
802
803
804 <table>
805 <tr sclass="tr" class="alt" align="left" valign="top">
3caedb5b
TB
806 <td smap="people_id">1</td>
807 <td smap="phone">(877) 255-3239</td>
808 <td smap="password">*********</td>
9b7a5679
TB
809 </tr>
810 </table>
811
3caedb5b 812In the table above, there are several attributes named C<< smap >>. If we have a hashref whose keys are the same:
9b7a5679
TB
813
814 my %data = (people_id => 888, phone => '444-4444', password => 'dont-you-dare-render');
815
816Then a single API call allows us to populate the HTML while excluding those ones we dont:
817
f25dca7f
TB
818 $tree->hashmap('sid' => \%data, ['password']);
819
9b7a5679 820
f25dca7f 821Note: the other way to prevent rendering some of the hash mapping is to not give that element the attr
9b7a5679
TB
822you plan to use for hash mapping.
823
f25dca7f
TB
824Also note: the function C<< hashmap >> has a simple easy-to-type API. Interally, it calls C<< hash_map >>
825(which has a more verbose keyword calling API). Thus, the above call to C<hashmap()> results in this call:
826
827 $tree->hash_map(hash => \%data, to_attr => 'sid', excluding => ['password']);
828
9b7a5679 829
67e78ff2 830=head3 $elem->replace_content(@new_elem)
831
832Replaces all of C<$elem>'s content with C<@new_elem>.
833
834=head3 $elem->wrap_content($wrapper_element)
835
836Wraps the existing content in the provided element. If the provided element
837happens to be a non-element, a push_content is performed instead.
838
839=head3 $elem->set_child_content(@look_down, $content)
840
841 This method looks down $tree using the criteria specified in @look_down using the the HTML::Element look_down() method.
842
843After finding the node, it detaches the node's content and pushes $content as the node's content.
844
3c14ea1e 845=head3 $tree->content_handler(%id_content)
67e78ff2 846
847This is a convenience method. Because the look_down criteria will often simply be:
848
849 id => 'fixme'
850
851to find things like:
852
853 <a id=fixme href=http://www.somesite.org>replace_content</a>
854
855You can call this method to shorten your typing a bit. You can simply type
856
857 $elem->content_handler( fixme => 'new text' )
858
859Instead of typing:
860
861 $elem->set_child_content(sid => 'fixme', 'new text')
862
3c14ea1e 863PLEASE NOTE: you can pass a hash whose keys are C<id>s and whose values are the content you want there and it will perform the replacement on each hash member:
864
865 my %id_content = (name => "Terrence Brannon",
866 email => 'tbrannon@in.com',
867 balance => 666,
868 content => $main_content);
869
870 $tree->content_handler(%id_content);
871
67e78ff2 872=head3 $tree->highlander($subtree_span_id, $conditionals, @conditionals_args)
873
874This allows for "if-then-else" style processing. Highlander was a movie in
875which only one would survive. Well, in terms of a tree when looking at a
876structure that you want to process in C<if-then-else> style, only one child
877will survive. For example, given this HTML template:
878
879 <span klass="highlander" id="age_dialog">
880 <span id="under10">
881 Hello, does your mother know you're
882 using her AOL account?
883 </span>
884 <span id="under18">
885 Sorry, you're not old enough to enter
886 (and too dumb to lie about your age)
887 </span>
888 <span id="welcome">
889 Welcome
890 </span>
891 </span>
892
893We only want one child of the C<span> tag with id C<age_dialog> to remain
894based on the age of the person visiting the page.
895
896So, let's setup a call that will prune the subtree as a function of age:
897
898 sub process_page {
899 my $age = shift;
900 my $tree = HTML::TreeBuilder->new_from_file('t/html/highlander.html');
901
902 $tree->highlander
903 (age_dialog =>
904 [
905 under10 => sub { $_[0] < 10} ,
906 under18 => sub { $_[0] < 18} ,
907 welcome => sub { 1 }
908 ],
909 $age
910 );
911
912And there we have it. If the age is less than 10, then the node with
913id C<under10> remains. For age less than 18, the node with id C<under18>
914remains.
915Otherwise our "else" condition fires and the child with id C<welcome> remains.
916
4b02c173 917=head3 $tree->passover($id_of_element)
918
919In some cases, you know exactly which element should survive. In this case,
920you can simply call C<passover> to remove it's siblings. For the HTML
921above, you could delete C<under10> and C<welcome> by simply calling:
922
923 $tree->passover('under18');
924
67e78ff2 925=head3 $tree->highlander2($tree, $conditionals, @conditionals_args)
926
927Right around the same time that C<table2()> came into being, Seamstress
928began to tackle tougher and tougher processing problems. It became clear that
929a more powerful highlander was needed... one that not only snipped the tree
930of the nodes that should not survive, but one that allows for
931post-processing of the survivor node. And one that was more flexible with
932how to find the nodes to snip.
933
934Thus (drum roll) C<highlander2()>.
935
936So let's look at our HTML which requires post-selection processing:
937
938 <span klass="highlander" id="age_dialog">
939 <span id="under10">
940 Hello, little <span id=age>AGE</span>-year old,
941 does your mother know you're using her AOL account?
942 </span>
943 <span id="under18">
944 Sorry, you're only <span id=age>AGE</span>
945 (and too dumb to lie about your age)
946 </span>
947 <span id="welcome">
948 Welcome, isn't it good to be <span id=age>AGE</span> years old?
949 </span>
950</span>
951
952In this case, a branch survives, but it has dummy data in it. We must take
953the surviving segment of HTML and rewrite the age C<span> with the age.
954Here is how we use C<highlander2()> to do so:
955
956 sub replace_age {
957 my $branch = shift;
958 my $age = shift;
959 $branch->look_down(id => 'age')->replace_content($age);
960 }
961
962 my $if_then = $tree->look_down(id => 'age_dialog');
963
964 $if_then->highlander2(
965 cond => [
966 under10 => [
967 sub { $_[0] < 10} ,
968 \&replace_age
969 ],
970 under18 => [
971 sub { $_[0] < 18} ,
972 \&replace_age
973 ],
974 welcome => [
975 sub { 1 },
976 \&replace_age
977 ]
978 ],
979 cond_arg => [ $age ]
980 );
981
982We pass it the tree (C<$if_then>), an arrayref of conditions
983(C<cond>) and an arrayref of arguments which are passed to the
984C<cond>s and to the replacement subs.
985
986The C<under10>, C<under18> and C<welcome> are id attributes in the
987tree of the siblings of which only one will survive. However,
988should you need to do
989more complex look-downs to find the survivor,
990then supply an array ref instead of a simple
991scalar:
992
993
994 $if_then->highlander2(
995 cond => [
996 [class => 'r12'] => [
997 sub { $_[0] < 10} ,
998 \&replace_age
999 ],
1000 [class => 'z22'] => [
1001 sub { $_[0] < 18} ,
1002 \&replace_age
1003 ],
1004 [class => 'w88'] => [
1005 sub { 1 },
1006 \&replace_age
1007 ]
1008 ],
1009 cond_arg => [ $age ]
1010 );
1011
1012
1013=head3 $tree->overwrite_attr($mutation_attr => $mutating_closures)
1014
1015This method is designed for taking a tree and reworking a set of nodes in
1016a stereotyped fashion. For instance let's say you have 3 remote image
1017archives, but you don't want to put long URLs in your img src
1018tags for reasons of abstraction, re-use and brevity. So instead you do this:
1019
1020 <img src="/img/smiley-face.jpg" fixup="src lnc">
1021 <img src="/img/hot-babe.jpg" fixup="src playboy">
1022 <img src="/img/footer.jpg" fixup="src foobar">
1023
1024and then when the tree of HTML is being processed, you make this call:
1025
1026 my %closures = (
1027 lnc => sub { my ($tree, $mute_node, $attr_value)= @_; "http://lnc.usc.edu$attr_value" },
1028 playboy => sub { my ($tree, $mute_node, $attr_value)= @_; "http://playboy.com$attr_value" }
1029 foobar => sub { my ($tree, $mute_node, $attr_value)= @_; "http://foobar.info$attr_value" }
1030 )
1031
1032 $tree->overwrite_attr(fixup => \%closures) ;
1033
1034and the tags come out modified like so:
1035
1036 <img src="http://lnc.usc.edu/img/smiley-face.jpg" fixup="src lnc">
1037 <img src="http://playboy.com/img/hot-babe.jpg" fixup="src playboy">
1038 <img src="http://foobar.info/img/footer.jpg" fixup="src foobar">
1039
1040=head3 $tree->mute_elem($mutation_attr => $mutating_closures, [ $post_hook ] )
1041
1042This is a generalization of C<overwrite_attr>. C<overwrite_attr>
1043assumes the return value of the
1044closure is supposed overwrite an attribute value and does it for you.
1045C<mute_elem> is a more general function which does nothing but
1046hand the closure the element and let it mutate it as it jolly well pleases :)
1047
1048In fact, here is the implementation of C<overwrite_attr>
1049to give you a taste of how C<mute_attr> is used:
1050
1051 sub overwrite_action {
1052 my ($mute_node, %X) = @_;
1053
1054 $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
1055 }
1056
1057
1058 sub HTML::Element::overwrite_attr {
1059 my $tree = shift;
1060
1061 $tree->mute_elem(@_, \&overwrite_action);
1062 }
1063
1064
1065
1066
9b7a5679
TB
1067=head2 Tree-Building Methods
1068
1069
1070
1071=head3 Unrolling an array via a single sample element (<ul> container)
67e78ff2 1072
1073This is best described by example. Given this HTML:
1074
1075 <strong>Here are the things I need from the store:</strong>
1076 <ul>
1077 <li class="store_items">Sample item</li>
1078 </ul>
1079
1080We can unroll it like so:
1081
1082 my $li = $tree->look_down(class => 'store_items');
1083
1084 my @items = qw(bread butter vodka);
1085
1086 $tree->iter($li => @items);
1087
1088To produce this:
1089
1090
1091 <html>
1092 <head></head>
1093 <body>Here are the things I need from the store:
1094 <ul>
1095 <li class="store_items">bread</li>
1096 <li class="store_items">butter</li>
1097 <li class="store_items">vodka</li>
1098 </ul>
1099 </body>
1100 </html>
1101
9b7a5679 1102=head3 Unrolling an array via n sample elements (<dl> container)
67e78ff2 1103
1104C<iter()> was fine for awhile, but some things
1105(e.g. definition lists) need a more general function to make them easy to
1106do. Hence C<iter2()>. This function will be explained by example of unrolling
1107a simple definition list.
1108
1109So here's our mock-up HTML from the designer:
1110
1111 <dl class="dual_iter" id="service_plan">
1112 <dt>
1113 Artist
1114 </dt>
1115 <dd>
1116 A person who draws blood.
1117 </dd>
1118
1119 <dt>
1120 Musician
1121 </dt>
1122 <dd>
1123 A clone of Iggy Pop.
1124 </dd>
1125
1126 <dt>
1127 Poet
1128 </dt>
1129 <dd>
1130 A relative of Edgar Allan Poe.
1131 </dd>
1132
1133 <dt class="adstyle">sample header</dt>
1134 <dd class="adstyle2">sample data</dd>
1135
1136 </dl>
1137
1138
1139And we want to unroll our data set:
1140
1141 my @items = (
1142 ['the pros' => 'never have to worry about service again'],
1143 ['the cons' => 'upfront extra charge on purchase'],
1144 ['our choice' => 'go with the extended service plan']
1145 );
1146
1147
1148Now, let's make this problem a bit harder to show off the power of C<iter2()>.
1149Let's assume that we want only the last <dt> and it's accompanying <dd>
1150(the one with "sample data") to be used as the sample data
1151for unrolling with our data set. Let's further assume that we want them to
1152remain in the final output.
1153
1154So now, the API to C<iter2()> will be discussed and we will explain how our
1155goal of getting our data into HTML fits into the API.
1156
1157=over 4
1158
1159=item * wrapper_ld
1160
1161This is how to look down and find the container of all the elements we will
1162be unrolling. The <dl> tag is the container for the dt and dd tags we will be
1163unrolling.
1164
1165If you pass an anonymous subroutine, then it is presumed that execution of
1166this subroutine will return the HTML::Element representing the container tag.
1167If you pass an array ref, then this will be dereferenced and passed to
1168C<HTML::Element::look_down()>.
1169
1170default value: C<< ['_tag' => 'dl'] >>
1171
1172Based on the mock HTML above, this default is fine for finding our container
1173tag. So let's move on.
1174
1175=item * wrapper_data
1176
1177This is an array reference of data that we will be putting into the container.
1178You must supply this. C<@items> above is our C<wrapper_data>.
1179
1180=item * wrapper_proc
1181
1182After we find the container via C<wrapper_ld>, we may want to pre-process
1183some aspect of this tree. In our case the first two sets of dt and dd need
1184to be removed, leaving the last dt and dd. So, we supply a C<wrapper_proc>
1185which will do this.
1186
1187default: undef
1188
1189=item * item_ld
1190
1191This anonymous subroutine returns an array ref of C<HTML::Element>s that will
1192be cloned and populated with item data
1193(item data is a "row" of C<wrapper_data>).
1194
1195default: returns an arrayref consisting of the dt and dd element inside the
1196container.
1197
1198=item * item_data
1199
1200This is a subroutine that takes C<wrapper_data> and retrieves one "row"
1201to be "pasted" into the array ref of C<HTML::Element>s found via C<item_ld>.
1202I hope that makes sense.
1203
1204default: shifts C<wrapper_data>.
1205
1206=item * item_proc
1207
1208This is a subroutine that takes the C<item_data> and the C<HTML::Element>s
1209found via C<item_ld> and produces an arrayref of C<HTML::Element>s which will
1210eventually be spliced into the container.
1211
1212Note that this subroutine MUST return the new items. This is done
1213So that more items than were passed in can be returned. This is
1214useful when, for example, you must return 2 dts for an input data item.
1215And when would you do this? When a single term has multiple spellings
1216for instance.
1217
1218default: expects C<item_data> to be an arrayref of two elements and
1219C<item_elems> to be an arrayref of two C<HTML::Element>s. It replaces the
1220content of the C<HTML::Element>s with the C<item_data>.
1221
1222=item * splice
1223
1224After building up an array of C<@item_elems>, the subroutine passed as
1225C<splice> will be given the parent container HTML::Element and the
1226C<@item_elems>. How the C<@item_elems> end up in the container is up to this
1227routine: it could put half of them in. It could unshift them or whatever.
1228
1229default: C<< $container->splice_content(0, 2, @item_elems) >>
1230In other words, kill the 2 sample elements with the newly generated
1231@item_elems
1232
1233=back
1234
1235So now that we have documented the API, let's see the call we need:
1236
1237 $tree->iter2(
1238 # default wrapper_ld ok.
1239 wrapper_data => \@items,
1240 wrapper_proc => sub {
1241 my ($container) = @_;
1242
1243 # only keep the last 2 dts and dds
1244 my @content_list = $container->content_list;
1245 $container->splice_content(0, @content_list - 2);
1246 },
1247
1248 # default item_ld is fine.
1249 # default item_data is fine.
1250 # default item_proc is fine.
1251 splice => sub {
1252 my ($container, @item_elems) = @_;
1253 $container->unshift_content(@item_elems);
1254 },
1255 debug => 1,
1256 );
1257
1258
9b7a5679
TB
1259
1260
1261=head3 Select Unrolling
67e78ff2 1262
1263The C<unroll_select> method has this API:
1264
1265 $tree->unroll_select(
1266 select_label => $id_label,
1267 option_value => $closure, # how to get option value from data row
1268 option_content => $closure, # how to get option content from data row
1269 option_selected => $closure, # boolean to decide if SELECTED
1270 data => $data # the data to be put into the SELECT
1271 data_iter => $closure # the thing that will get a row of data
3caedb5b
TB
1272 debug => $boolean,
1273 append => $boolean, # remove the sample <OPTION> data or append?
67e78ff2 1274 );
1275
1276Here's an example:
1277
1278 $tree->unroll_select(
1279 select_label => 'clan_list',
1280 option_value => sub { my $row = shift; $row->clan_id },
1281 option_content => sub { my $row = shift; $row->clan_name },
1282 option_selected => sub { my $row = shift; $row->selected },
1283 data => \@query_results,
3caedb5b
TB
1284 data_iter => sub { my $data = shift; $data->next },
1285 append => 0,
1286 debug => 0
1287 );
67e78ff2 1288
1289
1290
1291=head2 Tree-Building Methods: Table Generation
1292
1293Matthew Sisk has a much more intuitive (imperative)
1294way to generate tables via his module
1295L<HTML::ElementTable|HTML::ElementTable>.
1296However, for those with callback fever, the following
1297method is available. First, we look at a nuts and bolts way to build a table
1298using only standard L<HTML::Tree> API calls. Then the C<table> method
1299available here is discussed.
1300
1301=head3 Sample Model
1302
1303 package Simple::Class;
1304
1305 use Set::Array;
1306
1307 my @name = qw(bob bill brian babette bobo bix);
1308 my @age = qw(99 12 44 52 12 43);
1309 my @weight = qw(99 52 80 124 120 230);
1310
1311
1312 sub new {
1313 my $this = shift;
1314 bless {}, ref($this) || $this;
1315 }
1316
1317 sub load_data {
1318 my @data;
1319
1320 for (0 .. 5) {
1321 push @data, {
1322 age => $age[rand $#age] + int rand 20,
1323 name => shift @name,
1324 weight => $weight[rand $#weight] + int rand 40
1325 }
1326 }
1327
1328 Set::Array->new(@data);
1329 }
1330
1331
1332 1;
1333
1334
1335=head4 Sample Usage:
1336
1337 my $data = Simple::Class->load_data;
1338 ++$_->{age} for @$data
1339
1340=head3 Inline Code to Unroll a Table
1341
1342=head4 HTML
1343
1344 <html>
1345
1346 <table id="load_data">
1347
1348 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1349
1350 <tr id="iterate">
1351
1352 <td id="name"> NATURE BOY RIC FLAIR </td>
1353 <td id="age"> 35 </td>
1354 <td id="weight"> 220 </td>
1355
1356 </tr>
1357
1358 </table>
1359
1360 </html>
1361
1362
1363=head4 The manual way (*NOT* recommended)
1364
1365 require 'simple-class.pl';
1366 use HTML::Seamstress;
1367
1368 # load the view
1369 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
1370
1371 # load the model
1372 my $o = Simple::Class->new;
1373 my $data = $o->load_data;
1374
1375 # find the <table> and <tr>
1376 my $table_node = $seamstress->look_down('id', 'load_data');
1377 my $iter_node = $table_node->look_down('id', 'iterate');
1378 my $table_parent = $table_node->parent;
1379
1380
1381 # drop the sample <table> and <tr> from the HTML
1382 # only add them in if there is data in the model
1383 # this is achieved via the $add_table flag
1384
1385 $table_node->detach;
1386 $iter_node->detach;
1387 my $add_table;
1388
1389 # Get a row of model data
1390 while (my $row = shift @$data) {
1391
1392 # We got row data. Set the flag indicating ok to hook the table into the HTML
1393 ++$add_table;
1394
1395 # clone the sample <tr>
1396 my $new_iter_node = $iter_node->clone;
1397
1398 # find the tags labeled name age and weight and
1399 # set their content to the row data
1400 $new_iter_node->content_handler($_ => $row->{$_})
1401 for qw(name age weight);
1402
1403 $table_node->push_content($new_iter_node);
1404
1405 }
1406
1407 # reattach the table to the HTML tree if we loaded data into some table rows
1408
1409 $table_parent->push_content($table_node) if $add_table;
1410
1411 print $seamstress->as_HTML;
1412
1413
1414
1415=head3 $tree->table() : API call to Unroll a Table
1416
1417 require 'simple-class.pl';
1418 use HTML::Seamstress;
1419
1420 # load the view
1421 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
1422 # load the model
1423 my $o = Simple::Class->new;
1424
1425 $seamstress->table
1426 (
1427 # tell seamstress where to find the table, via the method call
1428 # ->look_down('id', $gi_table). Seamstress detaches the table from the
1429 # HTML tree automatically if no table rows can be built
1430
1431 gi_table => 'load_data',
1432
1433 # tell seamstress where to find the tr. This is a bit useless as
1434 # the <tr> usually can be found as the first child of the parent
1435
1436 gi_tr => 'iterate',
1437
1438 # the model data to be pushed into the table
1439
1440 table_data => $o->load_data,
1441
1442 # the way to take the model data and obtain one row
1443 # if the table data were a hashref, we would do:
1444 # my $key = (keys %$data)[0]; my $val = $data->{$key}; delete $data->{$key}
1445
1446 tr_data => sub { my ($self, $data) = @_;
1447 shift(@{$data}) ;
1448 },
1449
1450 # the way to take a row of data and fill the <td> tags
1451
1452 td_data => sub { my ($tr_node, $tr_data) = @_;
1453 $tr_node->content_handler($_ => $tr_data->{$_})
1454 for qw(name age weight) }
1455
1456 );
1457
1458
1459 print $seamstress->as_HTML;
1460
1461
1462
1463=head4 Looping over Multiple Sample Rows
1464
1465* HTML
1466
1467 <html>
1468
1469 <table id="load_data" CELLPADDING=8 BORDER=2>
1470
1471 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1472
1473 <tr id="iterate1" BGCOLOR="white" >
1474
1475 <td id="name"> NATURE BOY RIC FLAIR </td>
1476 <td id="age"> 35 </td>
1477 <td id="weight"> 220 </td>
1478
1479 </tr>
1480 <tr id="iterate2" BGCOLOR="#CCCC99">
1481
1482 <td id="name"> NATURE BOY RIC FLAIR </td>
1483 <td id="age"> 35 </td>
1484 <td id="weight"> 220 </td>
1485
1486 </tr>
1487
1488 </table>
1489
1490 </html>
1491
1492
1493* Only one change to last API call.
1494
1495This:
1496
1497 gi_tr => 'iterate',
1498
1499becomes this:
1500
1501 gi_tr => ['iterate1', 'iterate2']
1502
1503=head3 $tree->table2() : New API Call to Unroll a Table
1504
1505After 2 or 3 years with C<table()>, I began to develop
1506production websites with it and decided it needed a cleaner
1507interface, particularly in the area of handling the fact that
1508C<id> tags will be the same after cloning a table row.
1509
1510First, I will give a dry listing of the function's argument parameters.
1511This will not be educational most likely. A better way to understand how
1512to use the function is to read through the incremental unrolling of the
1513function's interface given in conversational style after the dry listing.
1514But take your pick. It's the same information given in two different
1515ways.
1516
1517=head4 Dry/technical parameter documentation
1518
1519C<< $tree->table2(%param) >> takes the following arguments:
1520
1521=over
1522
1523=item * C<< table_ld => $look_down >> : optional
1524
1525How to find the C<table> element in C<$tree>. If C<$look_down> is an
1526arrayref, then use C<look_down>. If it is a CODE ref, then call it,
1527passing it C<$tree>.
1528
1529Defaults to C<< ['_tag' => 'table'] >> if not passed in.
1530
1531=item * C<< table_data => $tabular_data >> : required
1532
1533The data to fill the table with. I<Must> be passed in.
1534
1535=item * C<< table_proc => $code_ref >> : not implemented
1536
1537A subroutine to do something to the table once it is found.
1538Not currently implemented. Not obviously necessary. Just
1539created because there is a C<tr_proc> and C<td_proc>.
1540
1541=item * C<< tr_ld => $look_down >> : optional
1542
1543Same as C<table_ld> but for finding the table row elements. Please note
1544that the C<tr_ld> is done on the table node that was found I<instead>
1545of the whole HTML tree. This makes sense. The C<tr>s that you want exist
1546below the table that was just found.
1547
1548Defaults to C<< ['_tag' => 'tr'] >> if not passed in.
1549
1550=item * C<< tr_data => $code_ref >> : optional
1551
1552How to take the C<table_data> and return a row. Defaults to:
1553
1554 sub { my ($self, $data) = @_;
1555 shift(@{$data}) ;
1556 }
1557
1558=item * C<< tr_proc => $code_ref >> : optional
1559
1560Something to do to the table row we are about to add to the
1561table we are making. Defaults to a routine which makes the C<id>
1562attribute unique:
1563
1564 sub {
1565 my ($self, $tr, $tr_data, $tr_base_id, $row_count) = @_;
1566 $tr->attr(id => sprintf "%s_%d", $tr_base_id, $row_count);
1567 }
1568
1569=item * C<< td_proc => $code_ref >> : required
1570
1571This coderef will take the row of data and operate on the C<td> cells that
1572are children of the C<tr>. See C<t/table2.t> for several usage examples.
1573
1574Here's a sample one:
1575
1576 sub {
1577 my ($tr, $data) = @_;
1578 my @td = $tr->look_down('_tag' => 'td');
1579 for my $i (0..$#td) {
1580 $td[$i]->splice_content(0, 1, $data->[$i]);
1581 }
1582 }
1583
1584=cut
1585
1586=head4 Conversational parameter documentation
1587
1588The first thing you need is a table. So we need a look down for that. If you
1589don't give one, it defaults to
1590
1591 ['_tag' => 'table']
1592
1593What good is a table to display in without data to display?!
1594So you must supply a scalar representing your tabular
1595data source. This scalar might be an array reference, a C<next>able iterator,
1596a DBI statement handle. Whatever it is, it can be iterated through to build
1597up rows of table data.
1598These two required fields (the way to find the table and the data to
1599display in the table) are C<table_ld> and C<table_data>
1600respectively. A little more on C<table_ld>. If this happens to be a CODE ref,
1601then execution
1602of the code ref is presumed to return the C<HTML::Element>
1603representing the table in the HTML tree.
1604
1605Next, we get the row or rows which serve as sample C<tr> elements by doing
1606a C<look_down> from the C<table_elem>. While normally one sample row
1607is enough to unroll a table, consider when you have alternating
1608table rows. This API call would need one of each row so that it can
1609cycle through the
1610sample rows as it loops through the data.
1611Alternatively, you could always just use one row and
1612make the necessary changes to the single C<tr> row by
1613mutating the element in C<tr_proc>,
1614discussed below. The default C<tr_ld> is
1615C<< ['_tag' => 'tr'] >> but you can overwrite it. Note well, if you overwrite
1616it with a subroutine, then it is expected that the subroutine will return
1617the C<HTML::Element>(s)
1618which are C<tr> element(s).
1619The reason a subroutine might be preferred is in the case
1620that the HTML designers gave you 8 sample C<tr> rows but only one
1621prototype row is needed.
1622So you can write a subroutine, to splice out the 7 rows you don't need
1623and leave the one sample
1624row remaining so that this API call can clone it and supply it to
1625the C<tr_proc> and C<td_proc> calls.
1626
1627Now, as we move through the table rows with table data,
1628we need to do two different things on
1629each table row:
1630
1631=over 4
1632
1633=item * get one row of data from the C<table_data> via C<tr_data>
1634
1635The default procedure assumes the C<table_data> is an array reference and
1636shifts a row off of it:
1637
1638 sub { my ($self, $data) = @_;
1639 shift(@{$data}) ;
1640 }
1641
1642Your function MUST return undef when there is no more rows to lay out.
1643
1644=item * take the C<tr> element and mutate it via C<tr_proc>
1645
1646The default procedure simply makes the id of the table row unique:
1647
1648 sub { my ($self, $tr, $tr_data, $row_count, $root_id) = @_;
1649 $tr->attr(id => sprintf "%s_%d", $root_id, $row_count);
1650 }
1651
1652=back
1653
1654Now that we have our row of data, we call C<td_proc> so that it can
1655take the data and the C<td> cells in this C<tr> and process them.
1656This function I<must> be supplied.
1657
1658
1659=head3 Whither a Table with No Rows
1660
1661Often when a table has no rows, we want to display a message
1662indicating this to the view. Use conditional processing to decide what
1663to display:
1664
1665 <span id=no_data>
1666 <table><tr><td>No Data is Good Data</td></tr></table>
1667 </span>
1668 <span id=load_data>
1669 <html>
1670
1671 <table id="load_data">
1672
1673 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1674
1675 <tr id="iterate">
1676
1677 <td id="name"> NATURE BOY RIC FLAIR </td>
1678 <td id="age"> 35 </td>
1679 <td id="weight"> 220 </td>
1680
1681 </tr>
1682
1683 </table>
1684
1685 </html>
1686
1687 </span>
1688
1689
1690
1691
1692=head1 SEE ALSO
1693
1694=over
1695
1696=item * L<HTML::Tree>
1697
1698A perl package for creating and manipulating HTML trees
1699
1700=item * L<HTML::ElementTable>
1701
1702An L<HTML::Tree> - based module which allows for manipulation of HTML
1703trees using cartesian coordinations.
1704
1705=item * L<HTML::Seamstress>
1706
1707An L<HTML::Tree> - based module inspired by
1708XMLC (L<http://xmlc.enhydra.org>), allowing for dynamic
1709HTML generation via tree rewriting.
1710
1711=head1 TODO
1712
1713=over
1714
1715=item * highlander2
1716
1717currently the API expects the subtrees to survive or be pruned to be
1718identified by id:
1719
1720 $if_then->highlander2([
1721 under10 => sub { $_[0] < 10} ,
1722 under18 => sub { $_[0] < 18} ,
1723 welcome => [
1724 sub { 1 },
1725 sub {
1726 my $branch = shift;
1727 $branch->look_down(id => 'age')->replace_content($age);
1728 }
1729 ]
1730 ],
1731 $age
1732 );
1733
1734but, it should be more flexible. the C<under10>, and C<under18> are
1735expected to be ids in the tree... but it is not hard to have a check to
1736see if this field is an array reference and if it, then to do a look
1737down instead:
1738
1739 $if_then->highlander2([
1740 [class => 'under10'] => sub { $_[0] < 10} ,
1741 [class => 'under18'] => sub { $_[0] < 18} ,
1742 [class => 'welcome'] => [
1743 sub { 1 },
1744 sub {
1745 my $branch = shift;
1746 $branch->look_down(id => 'age')->replace_content($age);
1747 }
1748 ]
1749 ],
1750 $age
1751 );
1752
1753
1754
1755=cut
1756
1757=head1 SEE ALSO
1758
1759L<HTML::Seamstress>
1760
f25dca7f 1761=head1 AUTHOR / SOURCE
67e78ff2 1762
1763Terrence Brannon, E<lt>tbone@cpan.orgE<gt>
1764
1765Many thanks to BARBIE for his RT bug report.
1766
f25dca7f
TB
1767The source is at L<http://github.com/metaperl/html-element-library/tree/master>
1768
67e78ff2 1769=head1 COPYRIGHT AND LICENSE
1770
1771Copyright (C) 2004 by Terrence Brannon
1772
1773This library is free software; you can redistribute it and/or modify
1774it under the same terms as Perl itself, either Perl version 5.8.4 or,
1775at your option, any later version of Perl 5 you may have available.
1776
1777
1778=cut
This page took 0.103279 seconds and 4 git commands to generate.