update git to 4.2.b
[html-element-library.git] / lib / HTML / Element / Library.pod
1 =head1 NAME
2
3 HTML::Element::Library - HTML::Element convenience functions
4
5 =head1 SYNOPSIS
6
7 use HTML::Element::Library;
8 use HTML::TreeBuilder;
9
10 =head1 DESCRIPTION
11
12 This method provides API calls for common actions on trees when using
13 L<HTML::Tree>.
14
15 =head1 METHODS
16
17 The test suite contains examples of each of these methods in a
18 file C<t/$method.t>
19
20 =head2 Positional Querying Methods
21
22 =head3 $elem->siblings
23
24 Return a list of all nodes under the same parent.
25
26 =head3 $elem->sibdex
27
28 Return the index of C<$elem> into the array of siblings of which it is
29 a part. L<HTML::ElementSuper> calls this method C<addr> but I don't think
30 that is a descriptive name. And such naming is deceptively close to the
31 C<address> function of C<HTML::Element>. HOWEVER, in the interest of
32 backwards compatibility, both methods are available.
33
34 =head3 $elem->addr
35
36 Same as sibdex
37
38 =head3 $elem->position()
39
40 Returns the coordinates of this element in the tree it inhabits.
41 This is accomplished by succesively calling addr() on ancestor
42 elements until either a) an element that does not support these
43 methods is found, or b) there are no more parents. The resulting
44 list is the n-dimensional coordinates of the element in the tree.
45
46 =head2 Element Decoration Methods
47
48 =head3 HTML::Element::Library::super_literal($text)
49
50 In L<HTML::Element>, Sean Burke discusses super-literals. They are
51 text which does not get escaped. Great for includng Javascript in
52 HTML. Also great for including foreign language into a document.
53
54 So, you basically toss C<super_literal> your text and back comes
55 your text wrapped in a C<~literal> element.
56
57 One of these days, I'll around to writing a nice C<EXPORT> section.
58
59 =head2 Tree Rewriting Methods
60
61 =head3 Simplifying calls to HTML::FillInForm
62
63 Since HTML::FillInForm gets and returns strings, using HTML::Element instances
64 becomes tedious:
65
66 1. Seamstress has an HTML tree that it wants the form filled in on
67 2. Seamstress converts this tree to a string
68 3. FillInForm parses the string into an HTML tree and then fills in the form
69 4. FillInForm converts the HTML tree to a string
70 5. Seamstress re-parses the HTML for additional processing
71
72 I've filed a bug about this:
73 L<https://rt.cpan.org/Ticket/Display.html?id=44105>
74
75 This function, fillinform,
76 allows you to pass a tree to fillinform (along with your data structure) and
77 get back a tree:
78
79 my $new_tree = $html_tree->fillinform($data_structure);
80
81
82 =head3 Mapping a hashref to HTML elements
83
84 It is very common to get a hashref of data from some external source - flat file, database, XML, etc.
85 Therefore, it is important to have a convenient way of mapping this data to HTML.
86
87 As it turns out, there are 3 ways to do this in HTML::Element::Library.
88 The most strict and structured way to do this is with
89 C<content_handler>. Two other methods, C<hashmap> and C<datamap> require less manual mapping and may prove
90 even more easy to use in certain cases.
91
92 As is usual with Perl, a practical example is always best. So let's take some sample HTML:
93
94 <h1>user data</h1>
95 <span id="name">?</span>
96 <span id="email">?</span>
97 <span id="gender">?</span>
98
99 Now, let's say our data structure is this:
100
101 $ref = { email => 'jim@beam.com', gender => 'lots' } ;
102
103 And let's start with the most strict way to get what you want:
104
105 $tree->content_handler(email => $ref->{email} , gender => $ref->{gender}) ;
106
107
108 In this case, you manually state the mapping between id tags and hashref keys and
109 then C<content_handler> retrieves the hashref data and pops it in the specified place.
110
111 Now let's look at the two (actually 2 and a half) other hash-mapping methods.
112
113 $tree->hashmap(id => $ref);
114
115 Now, what this function does is super-destructive. It finds every element in the tree
116 with an attribute named id (since 'id' is a parameter, it could find every element with
117 some other attribute also) and replaces the content of those elements with the hashref
118 value.
119
120 So, in the case above, the
121
122 <span id="name">?</span>
123
124 would come out as
125
126 <span id="name"></span>
127
128 (it would be blank) - because there is nothing in the hash with that value, so it substituted
129
130 $ref->{name}
131
132 which was blank and emptied the contents.
133
134 Now, let's assume we want to protect name from being auto-assigned. Here is what you do:
135
136 $tree->hashmap(id => $ref, ['name']);
137
138 That last array ref is an exclusion list.
139
140 But wouldnt it be nice if you could do a hashmap, but only assigned things which are defined
141 in the hashref? C<< defmap() >> to the rescue:
142
143 $tree->defmap(id => $ref);
144
145 does just that, so
146
147 <span id="name">?</span>
148
149 would be left alone.
150
151
152 =head4 $elem->hashmap($attr_name, \%hashref, \@excluded, $debug)
153
154 This method is designed to take a hashref and populate a series of elements. For example:
155
156
157 <table>
158 <tr sclass="tr" class="alt" align="left" valign="top">
159 <td smap="people_id">1</td>
160 <td smap="phone">(877) 255-3239</td>
161 <td smap="password">*********</td>
162 </tr>
163 </table>
164
165 In the table above, there are several attributes named C<< smap >>. If we have a hashref whose keys are the same:
166
167 my %data = (people_id => 888, phone => '444-4444', password => 'dont-you-dare-render');
168
169 Then a single API call allows us to populate the HTML while excluding those ones we dont:
170
171 $tree->hashmap(smap => \%data, ['password']);
172
173
174 Note: the other way to prevent rendering some of the hash mapping is to not give that element the attr
175 you plan to use for hash mapping.
176
177 Also note: the function C<< hashmap >> has a simple easy-to-type API. Interally, it calls C<< hash_map >>
178 (which has a more verbose keyword calling API). Thus, the above call to C<hashmap()> results in this call:
179
180 $tree->hash_map(hash => \%data, to_attr => 'sid', excluding => ['password']);
181
182 =head4 $elem->defmap($attr_name, \%hashref, $debug)
183
184 C<defmap> was described above.
185
186
187 =head4 $elem->content_handler(%hashref)
188
189 C<content_handler> is described below.
190
191
192 =head3 $elem->replace_content(@new_elem)
193
194 Replaces all of C<$elem>'s content with C<@new_elem>.
195
196 =head3 $elem->wrap_content($wrapper_element)
197
198 Wraps the existing content in the provided element. If the provided element
199 happens to be a non-element, a push_content is performed instead.
200
201 =head3 $elem->set_child_content(@look_down, $content)
202
203 This method looks down $tree using the criteria specified in @look_down using the the HTML::Element look_down() method.
204
205 After finding the node, it detaches the node's content and pushes $content as the node's content.
206
207 =head3 $tree->content_handler(%id_content)
208
209 This is a convenience method. Because the look_down criteria will often simply be:
210
211 id => 'fixme'
212
213 to find things like:
214
215 <a id=fixme href=http://www.somesite.org>replace_content</a>
216
217 You can call this method to shorten your typing a bit. You can simply type
218
219 $elem->content_handler( fixme => 'new text' )
220
221 Instead of typing:
222
223 $elem->set_child_content(sid => 'fixme', 'new text')
224
225 ALSO 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:
226
227 my %id_content = (name => "Terrence Brannon",
228 email => 'tbrannon@in.com',
229 balance => 666,
230 content => $main_content);
231
232 $tree->content_handler(%id_content);
233
234 =head3 $tree->highlander($subtree_span_id, $conditionals, @conditionals_args)
235
236 This allows for "if-then-else" style processing. Highlander was a movie in
237 which only one would survive. Well, in terms of a tree when looking at a
238 structure that you want to process in C<if-then-else> style, only one child
239 will survive. For example, given this HTML template:
240
241 <span klass="highlander" id="age_dialog">
242 <span id="under10">
243 Hello, does your mother know you're
244 using her AOL account?
245 </span>
246 <span id="under18">
247 Sorry, you're not old enough to enter
248 (and too dumb to lie about your age)
249 </span>
250 <span id="welcome">
251 Welcome
252 </span>
253 </span>
254
255 We only want one child of the C<span> tag with id C<age_dialog> to remain
256 based on the age of the person visiting the page.
257
258 So, let's setup a call that will prune the subtree as a function of age:
259
260 sub process_page {
261 my $age = shift;
262 my $tree = HTML::TreeBuilder->new_from_file('t/html/highlander.html');
263
264 $tree->highlander
265 (age_dialog =>
266 [
267 under10 => sub { $_[0] < 10} ,
268 under18 => sub { $_[0] < 18} ,
269 welcome => sub { 1 }
270 ],
271 $age
272 );
273
274 And there we have it. If the age is less than 10, then the node with
275 id C<under10> remains. For age less than 18, the node with id C<under18>
276 remains.
277 Otherwise our "else" condition fires and the child with id C<welcome> remains.
278
279 =head3 $tree->passover(@id_of_element)
280
281 In some cases, you know exactly which element(s) should survive. In this case,
282 you can simply call C<passover> to remove it's (their) siblings. For the HTML
283 above, you could delete C<under10> and C<welcome> by simply calling:
284
285 $tree->passover('under18');
286
287 Because passover takes an array, you can specify several children to preserve.
288
289 =head3 $tree->highlander2($tree, $conditionals, @conditionals_args)
290
291 Right around the same time that C<table2()> came into being, Seamstress
292 began to tackle tougher and tougher processing problems. It became clear that
293 a more powerful highlander was needed... one that not only snipped the tree
294 of the nodes that should not survive, but one that allows for
295 post-processing of the survivor node. And one that was more flexible with
296 how to find the nodes to snip.
297
298 Thus (drum roll) C<highlander2()>.
299
300 So let's look at our HTML which requires post-selection processing:
301
302 <span klass="highlander" id="age_dialog">
303 <span id="under10">
304 Hello, little <span id=age>AGE</span>-year old,
305 does your mother know you're using her AOL account?
306 </span>
307 <span id="under18">
308 Sorry, you're only <span id=age>AGE</span>
309 (and too dumb to lie about your age)
310 </span>
311 <span id="welcome">
312 Welcome, isn't it good to be <span id=age>AGE</span> years old?
313 </span>
314 </span>
315
316 In this case, a branch survives, but it has dummy data in it. We must take
317 the surviving segment of HTML and rewrite the age C<span> with the age.
318 Here is how we use C<highlander2()> to do so:
319
320 sub replace_age {
321 my $branch = shift;
322 my $age = shift;
323 $branch->look_down(id => 'age')->replace_content($age);
324 }
325
326 my $if_then = $tree->look_down(id => 'age_dialog');
327
328 $if_then->highlander2(
329 cond => [
330 under10 => [
331 sub { $_[0] < 10} ,
332 \&replace_age
333 ],
334 under18 => [
335 sub { $_[0] < 18} ,
336 \&replace_age
337 ],
338 welcome => [
339 sub { 1 },
340 \&replace_age
341 ]
342 ],
343 cond_arg => [ $age ]
344 );
345
346 We pass it the tree (C<$if_then>), an arrayref of conditions
347 (C<cond>) and an arrayref of arguments which are passed to the
348 C<cond>s and to the replacement subs.
349
350 The C<under10>, C<under18> and C<welcome> are id attributes in the
351 tree of the siblings of which only one will survive. However,
352 should you need to do
353 more complex look-downs to find the survivor,
354 then supply an array ref instead of a simple
355 scalar:
356
357
358 $if_then->highlander2(
359 cond => [
360 [class => 'r12'] => [
361 sub { $_[0] < 10} ,
362 \&replace_age
363 ],
364 [class => 'z22'] => [
365 sub { $_[0] < 18} ,
366 \&replace_age
367 ],
368 [class => 'w88'] => [
369 sub { 1 },
370 \&replace_age
371 ]
372 ],
373 cond_arg => [ $age ]
374 );
375
376
377 =head3 $tree->overwrite_attr($mutation_attr => $mutating_closures)
378
379 This method is designed for taking a tree and reworking a set of nodes in
380 a stereotyped fashion. For instance let's say you have 3 remote image
381 archives, but you don't want to put long URLs in your img src
382 tags for reasons of abstraction, re-use and brevity. So instead you do this:
383
384 <img src="/img/smiley-face.jpg" fixup="src lnc">
385 <img src="/img/hot-babe.jpg" fixup="src playboy">
386 <img src="/img/footer.jpg" fixup="src foobar">
387
388 and then when the tree of HTML is being processed, you make this call:
389
390 my %closures = (
391 lnc => sub { my ($tree, $mute_node, $attr_value)= @_; "http://lnc.usc.edu$attr_value" },
392 playboy => sub { my ($tree, $mute_node, $attr_value)= @_; "http://playboy.com$attr_value" }
393 foobar => sub { my ($tree, $mute_node, $attr_value)= @_; "http://foobar.info$attr_value" }
394 )
395
396 $tree->overwrite_attr(fixup => \%closures) ;
397
398 and the tags come out modified like so:
399
400 <img src="http://lnc.usc.edu/img/smiley-face.jpg" fixup="src lnc">
401 <img src="http://playboy.com/img/hot-babe.jpg" fixup="src playboy">
402 <img src="http://foobar.info/img/footer.jpg" fixup="src foobar">
403
404 =head3 $tree->mute_elem($mutation_attr => $mutating_closures, [ $post_hook ] )
405
406 This is a generalization of C<overwrite_attr>. C<overwrite_attr>
407 assumes the return value of the
408 closure is supposed overwrite an attribute value and does it for you.
409 C<mute_elem> is a more general function which does nothing but
410 hand the closure the element and let it mutate it as it jolly well pleases :)
411
412 In fact, here is the implementation of C<overwrite_attr>
413 to give you a taste of how C<mute_attr> is used:
414
415 sub overwrite_action {
416 my ($mute_node, %X) = @_;
417
418 $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
419 }
420
421
422 sub HTML::Element::overwrite_attr {
423 my $tree = shift;
424
425 $tree->mute_elem(@_, \&overwrite_action);
426 }
427
428
429
430
431 =head2 Tree-Building Methods
432
433
434
435 =head3 Unrolling an array via a single sample element (<ul> container)
436
437 This is best described by example. Given this HTML:
438
439 <strong>Here are the things I need from the store:</strong>
440 <ul>
441 <li class="store_items">Sample item</li>
442 </ul>
443
444 We can unroll it like so:
445
446 my $li = $tree->look_down(class => 'store_items');
447
448 my @items = qw(bread butter vodka);
449
450 $tree->iter($li => @items);
451
452 To produce this:
453
454
455 <html>
456 <head></head>
457 <body>Here are the things I need from the store:
458 <ul>
459 <li class="store_items">bread</li>
460 <li class="store_items">butter</li>
461 <li class="store_items">vodka</li>
462 </ul>
463 </body>
464 </html>
465
466 Now, you might be wondering why the API call is:
467
468 $tree->iter($li => @items)
469
470 instead of:
471
472 $li->iter(@items)
473
474 and there is no good answer. The latter would be more concise and it is what I
475 should have done.
476
477 =head3 Unrolling an array via n sample elements (<dl> container)
478
479 C<iter()> was fine for awhile, but some things
480 (e.g. definition lists) need a more general function to make them easy to
481 do. Hence C<iter2()>. This function will be explained by example of unrolling
482 a simple definition list.
483
484 So here's our mock-up HTML from the designer:
485
486 <dl class="dual_iter" id="service_plan">
487 <dt>
488 Artist
489 </dt>
490 <dd>
491 A person who draws blood.
492 </dd>
493
494 <dt>
495 Musician
496 </dt>
497 <dd>
498 A clone of Iggy Pop.
499 </dd>
500
501 <dt>
502 Poet
503 </dt>
504 <dd>
505 A relative of Edgar Allan Poe.
506 </dd>
507
508 <dt class="adstyle">sample header</dt>
509 <dd class="adstyle2">sample data</dd>
510
511 </dl>
512
513
514 And we want to unroll our data set:
515
516 my @items = (
517 ['the pros' => 'never have to worry about service again'],
518 ['the cons' => 'upfront extra charge on purchase'],
519 ['our choice' => 'go with the extended service plan']
520 );
521
522
523 Now, let's make this problem a bit harder to show off the power of C<iter2()>.
524 Let's assume that we want only the last <dt> and it's accompanying <dd>
525 (the one with "sample data") to be used as the sample data
526 for unrolling with our data set. Let's further assume that we want them to
527 remain in the final output.
528
529 So now, the API to C<iter2()> will be discussed and we will explain how our
530 goal of getting our data into HTML fits into the API.
531
532 =over 4
533
534 =item * wrapper_ld
535
536 This is how to look down and find the container of all the elements we will
537 be unrolling. The <dl> tag is the container for the dt and dd tags we will be
538 unrolling.
539
540 If you pass an anonymous subroutine, then it is presumed that execution of
541 this subroutine will return the HTML::Element representing the container tag.
542 If you pass an array ref, then this will be dereferenced and passed to
543 C<HTML::Element::look_down()>.
544
545 default value: C<< ['_tag' => 'dl'] >>
546
547 Based on the mock HTML above, this default is fine for finding our container
548 tag. So let's move on.
549
550 =item * wrapper_data
551
552 This is an array reference of data that we will be putting into the container.
553 You must supply this. C<@items> above is our C<wrapper_data>.
554
555 =item * wrapper_proc
556
557 After we find the container via C<wrapper_ld>, we may want to pre-process
558 some aspect of this tree. In our case the first two sets of dt and dd need
559 to be removed, leaving the last dt and dd. So, we supply a C<wrapper_proc>
560 which will do this.
561
562 default: undef
563
564 =item * item_ld
565
566 This anonymous subroutine returns an array ref of C<HTML::Element>s that will
567 be cloned and populated with item data
568 (item data is a "row" of C<wrapper_data>).
569
570 default: returns an arrayref consisting of the dt and dd element inside the
571 container.
572
573 =item * item_data
574
575 This is a subroutine that takes C<wrapper_data> and retrieves one "row"
576 to be "pasted" into the array ref of C<HTML::Element>s found via C<item_ld>.
577 I hope that makes sense.
578
579 default: shifts C<wrapper_data>.
580
581 =item * item_proc
582
583 This is a subroutine that takes the C<item_data> and the C<HTML::Element>s
584 found via C<item_ld> and produces an arrayref of C<HTML::Element>s which will
585 eventually be spliced into the container.
586
587 Note that this subroutine MUST return the new items. This is done
588 So that more items than were passed in can be returned. This is
589 useful when, for example, you must return 2 dts for an input data item.
590 And when would you do this? When a single term has multiple spellings
591 for instance.
592
593 default: expects C<item_data> to be an arrayref of two elements and
594 C<item_elems> to be an arrayref of two C<HTML::Element>s. It replaces the
595 content of the C<HTML::Element>s with the C<item_data>.
596
597 =item * splice
598
599 After building up an array of C<@item_elems>, the subroutine passed as
600 C<splice> will be given the parent container HTML::Element and the
601 C<@item_elems>. How the C<@item_elems> end up in the container is up to this
602 routine: it could put half of them in. It could unshift them or whatever.
603
604 default: C<< $container->splice_content(0, 2, @item_elems) >>
605 In other words, kill the 2 sample elements with the newly generated
606 @item_elems
607
608 =back
609
610 So now that we have documented the API, let's see the call we need:
611
612 $tree->iter2(
613 # default wrapper_ld ok.
614 wrapper_data => \@items,
615 wrapper_proc => sub {
616 my ($container) = @_;
617
618 # only keep the last 2 dts and dds
619 my @content_list = $container->content_list;
620 $container->splice_content(0, @content_list - 2);
621 },
622
623 # default item_ld is fine.
624 # default item_data is fine.
625 # default item_proc is fine.
626 splice => sub {
627 my ($container, @item_elems) = @_;
628 $container->unshift_content(@item_elems);
629 },
630 debug => 1,
631 );
632
633
634
635
636 =head3 Select Unrolling
637
638 The C<unroll_select> method has this API:
639
640 $tree->unroll_select(
641 select_label => $id_label,
642 option_value => $closure, # how to get option value from data row
643 option_content => $closure, # how to get option content from data row
644 option_selected => $closure, # boolean to decide if SELECTED
645 data => $data # the data to be put into the SELECT
646 data_iter => $closure # the thing that will get a row of data
647 debug => $boolean,
648 append => $boolean, # remove the sample <OPTION> data or append?
649 );
650
651 Here's an example:
652
653 $tree->unroll_select(
654 select_label => 'clan_list',
655 option_value => sub { my $row = shift; $row->clan_id },
656 option_content => sub { my $row = shift; $row->clan_name },
657 option_selected => sub { my $row = shift; $row->selected },
658 data => \@query_results,
659 data_iter => sub { my $data = shift; $data->next },
660 append => 0,
661 debug => 0
662 );
663
664
665
666 =head2 Tree-Building Methods: Table Generation
667
668 Matthew Sisk has a much more intuitive (imperative)
669 way to generate tables via his module
670 L<HTML::ElementTable|HTML::ElementTable>.
671 However, for those with callback fever, the following
672 method is available. First, we look at a nuts and bolts way to build a table
673 using only standard L<HTML::Tree> API calls. Then the C<table> method
674 available here is discussed.
675
676 =head3 Sample Model
677
678 package Simple::Class;
679
680 use Set::Array;
681
682 my @name = qw(bob bill brian babette bobo bix);
683 my @age = qw(99 12 44 52 12 43);
684 my @weight = qw(99 52 80 124 120 230);
685
686
687 sub new {
688 my $this = shift;
689 bless {}, ref($this) || $this;
690 }
691
692 sub load_data {
693 my @data;
694
695 for (0 .. 5) {
696 push @data, {
697 age => $age[rand $#age] + int rand 20,
698 name => shift @name,
699 weight => $weight[rand $#weight] + int rand 40
700 }
701 }
702
703 Set::Array->new(@data);
704 }
705
706
707 1;
708
709
710 =head4 Sample Usage:
711
712 my $data = Simple::Class->load_data;
713 ++$_->{age} for @$data
714
715 =head3 Inline Code to Unroll a Table
716
717 =head4 HTML
718
719 <html>
720
721 <table id="load_data">
722
723 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
724
725 <tr id="iterate">
726
727 <td id="name"> NATURE BOY RIC FLAIR </td>
728 <td id="age"> 35 </td>
729 <td id="weight"> 220 </td>
730
731 </tr>
732
733 </table>
734
735 </html>
736
737
738 =head4 The manual way (*NOT* recommended)
739
740 require 'simple-class.pl';
741 use HTML::Seamstress;
742
743 # load the view
744 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
745
746 # load the model
747 my $o = Simple::Class->new;
748 my $data = $o->load_data;
749
750 # find the <table> and <tr>
751 my $table_node = $seamstress->look_down('id', 'load_data');
752 my $iter_node = $table_node->look_down('id', 'iterate');
753 my $table_parent = $table_node->parent;
754
755
756 # drop the sample <table> and <tr> from the HTML
757 # only add them in if there is data in the model
758 # this is achieved via the $add_table flag
759
760 $table_node->detach;
761 $iter_node->detach;
762 my $add_table;
763
764 # Get a row of model data
765 while (my $row = shift @$data) {
766
767 # We got row data. Set the flag indicating ok to hook the table into the HTML
768 ++$add_table;
769
770 # clone the sample <tr>
771 my $new_iter_node = $iter_node->clone;
772
773 # find the tags labeled name age and weight and
774 # set their content to the row data
775 $new_iter_node->content_handler($_ => $row->{$_})
776 for qw(name age weight);
777
778 $table_node->push_content($new_iter_node);
779
780 }
781
782 # reattach the table to the HTML tree if we loaded data into some table rows
783
784 $table_parent->push_content($table_node) if $add_table;
785
786 print $seamstress->as_HTML;
787
788
789
790 =head3 $tree->table() : API call to Unroll a Table
791
792 require 'simple-class.pl';
793 use HTML::Seamstress;
794
795 # load the view
796 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
797 # load the model
798 my $o = Simple::Class->new;
799
800 $seamstress->table
801 (
802 # tell seamstress where to find the table, via the method call
803 # ->look_down('id', $gi_table). Seamstress detaches the table from the
804 # HTML tree automatically if no table rows can be built
805
806 gi_table => 'load_data',
807
808 # tell seamstress where to find the tr. This is a bit useless as
809 # the <tr> usually can be found as the first child of the parent
810
811 gi_tr => 'iterate',
812
813 # the model data to be pushed into the table
814
815 table_data => $o->load_data,
816
817 # the way to take the model data and obtain one row
818 # if the table data were a hashref, we would do:
819 # my $key = (keys %$data)[0]; my $val = $data->{$key}; delete $data->{$key}
820
821 tr_data => sub { my ($self, $data) = @_;
822 shift(@{$data}) ;
823 },
824
825 # the way to take a row of data and fill the <td> tags
826
827 td_data => sub { my ($tr_node, $tr_data) = @_;
828 $tr_node->content_handler($_ => $tr_data->{$_})
829 for qw(name age weight) }
830
831 );
832
833
834 print $seamstress->as_HTML;
835
836
837
838 =head4 Looping over Multiple Sample Rows
839
840 * HTML
841
842 <html>
843
844 <table id="load_data" CELLPADDING=8 BORDER=2>
845
846 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
847
848 <tr id="iterate1" BGCOLOR="white" >
849
850 <td id="name"> NATURE BOY RIC FLAIR </td>
851 <td id="age"> 35 </td>
852 <td id="weight"> 220 </td>
853
854 </tr>
855 <tr id="iterate2" BGCOLOR="#CCCC99">
856
857 <td id="name"> NATURE BOY RIC FLAIR </td>
858 <td id="age"> 35 </td>
859 <td id="weight"> 220 </td>
860
861 </tr>
862
863 </table>
864
865 </html>
866
867
868 * Only one change to last API call.
869
870 This:
871
872 gi_tr => 'iterate',
873
874 becomes this:
875
876 gi_tr => ['iterate1', 'iterate2']
877
878 =head3 $tree->table2() : New API Call to Unroll a Table
879
880 After 2 or 3 years with C<table()>, I began to develop
881 production websites with it and decided it needed a cleaner
882 interface, particularly in the area of handling the fact that
883 C<id> tags will be the same after cloning a table row.
884
885 First, I will give a dry listing of the function's argument parameters.
886 This will not be educational most likely. A better way to understand how
887 to use the function is to read through the incremental unrolling of the
888 function's interface given in conversational style after the dry listing.
889 But take your pick. It's the same information given in two different
890 ways.
891
892 =head4 Dry/technical parameter documentation
893
894 C<< $tree->table2(%param) >> takes the following arguments:
895
896 =over
897
898 =item * C<< table_ld => $look_down >> : optional
899
900 How to find the C<table> element in C<$tree>. If C<$look_down> is an
901 arrayref, then use C<look_down>. If it is a CODE ref, then call it,
902 passing it C<$tree>.
903
904 Defaults to C<< ['_tag' => 'table'] >> if not passed in.
905
906 =item * C<< table_data => $tabular_data >> : required
907
908 The data to fill the table with. I<Must> be passed in.
909
910 =item * C<< table_proc => $code_ref >> : not implemented
911
912 A subroutine to do something to the table once it is found.
913 Not currently implemented. Not obviously necessary. Just
914 created because there is a C<tr_proc> and C<td_proc>.
915
916 =item * C<< tr_ld => $look_down >> : optional
917
918 Same as C<table_ld> but for finding the table row elements. Please note
919 that the C<tr_ld> is done on the table node that was found I<instead>
920 of the whole HTML tree. This makes sense. The C<tr>s that you want exist
921 below the table that was just found.
922
923 Defaults to C<< ['_tag' => 'tr'] >> if not passed in.
924
925 =item * C<< tr_data => $code_ref >> : optional
926
927 How to take the C<table_data> and return a row. Defaults to:
928
929 sub { my ($self, $data) = @_;
930 shift(@{$data}) ;
931 }
932
933 =item * C<< tr_proc => $code_ref >> : optional
934
935 Something to do to the table row we are about to add to the
936 table we are making. Defaults to a routine which makes the C<id>
937 attribute unique:
938
939 sub {
940 my ($self, $tr, $tr_data, $tr_base_id, $row_count) = @_;
941 $tr->attr(id => sprintf "%s_%d", $tr_base_id, $row_count);
942 }
943
944 =item * C<< td_proc => $code_ref >> : required
945
946 This coderef will take the row of data and operate on the C<td> cells that
947 are children of the C<tr>. See C<t/table2.t> for several usage examples.
948
949 Here's a sample one:
950
951 sub {
952 my ($tr, $data) = @_;
953 my @td = $tr->look_down('_tag' => 'td');
954 for my $i (0..$#td) {
955 $td[$i]->splice_content(0, 1, $data->[$i]);
956 }
957 }
958
959 =cut
960
961 =head4 Conversational parameter documentation
962
963 The first thing you need is a table. So we need a look down for that. If you
964 don't give one, it defaults to
965
966 ['_tag' => 'table']
967
968 What good is a table to display in without data to display?!
969 So you must supply a scalar representing your tabular
970 data source. This scalar might be an array reference, a C<next>able iterator,
971 a DBI statement handle. Whatever it is, it can be iterated through to build
972 up rows of table data.
973 These two required fields (the way to find the table and the data to
974 display in the table) are C<table_ld> and C<table_data>
975 respectively. A little more on C<table_ld>. If this happens to be a CODE ref,
976 then execution
977 of the code ref is presumed to return the C<HTML::Element>
978 representing the table in the HTML tree.
979
980 Next, we get the row or rows which serve as sample C<tr> elements by doing
981 a C<look_down> from the C<table_elem>. While normally one sample row
982 is enough to unroll a table, consider when you have alternating
983 table rows. This API call would need one of each row so that it can
984 cycle through the
985 sample rows as it loops through the data.
986 Alternatively, you could always just use one row and
987 make the necessary changes to the single C<tr> row by
988 mutating the element in C<tr_proc>,
989 discussed below. The default C<tr_ld> is
990 C<< ['_tag' => 'tr'] >> but you can overwrite it. Note well, if you overwrite
991 it with a subroutine, then it is expected that the subroutine will return
992 the C<HTML::Element>(s)
993 which are C<tr> element(s).
994 The reason a subroutine might be preferred is in the case
995 that the HTML designers gave you 8 sample C<tr> rows but only one
996 prototype row is needed.
997 So you can write a subroutine, to splice out the 7 rows you don't need
998 and leave the one sample
999 row remaining so that this API call can clone it and supply it to
1000 the C<tr_proc> and C<td_proc> calls.
1001
1002 Now, as we move through the table rows with table data,
1003 we need to do two different things on
1004 each table row:
1005
1006 =over 4
1007
1008 =item * get one row of data from the C<table_data> via C<tr_data>
1009
1010 The default procedure assumes the C<table_data> is an array reference and
1011 shifts a row off of it:
1012
1013 sub { my ($self, $data) = @_;
1014 shift(@{$data}) ;
1015 }
1016
1017 Your function MUST return undef when there is no more rows to lay out.
1018
1019 =item * take the C<tr> element and mutate it via C<tr_proc>
1020
1021 The default procedure simply makes the id of the table row unique:
1022
1023 sub { my ($self, $tr, $tr_data, $row_count, $root_id) = @_;
1024 $tr->attr(id => sprintf "%s_%d", $root_id, $row_count);
1025 }
1026
1027 =back
1028
1029 Now that we have our row of data, we call C<td_proc> so that it can
1030 take the data and the C<td> cells in this C<tr> and process them.
1031 This function I<must> be supplied.
1032
1033
1034 =head3 Whither a Table with No Rows
1035
1036 Often when a table has no rows, we want to display a message
1037 indicating this to the view. Use conditional processing to decide what
1038 to display:
1039
1040 <span id=no_data>
1041 <table><tr><td>No Data is Good Data</td></tr></table>
1042 </span>
1043 <span id=load_data>
1044 <html>
1045
1046 <table id="load_data">
1047
1048 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1049
1050 <tr id="iterate">
1051
1052 <td id="name"> NATURE BOY RIC FLAIR </td>
1053 <td id="age"> 35 </td>
1054 <td id="weight"> 220 </td>
1055
1056 </tr>
1057
1058 </table>
1059
1060 </html>
1061
1062 </span>
1063
1064
1065
1066
1067 =head1 SEE ALSO
1068
1069 =over
1070
1071 =item * L<HTML::Tree>
1072
1073 A perl package for creating and manipulating HTML trees
1074
1075 =item * L<HTML::ElementTable>
1076
1077 An L<HTML::Tree> - based module which allows for manipulation of HTML
1078 trees using cartesian coordinations.
1079
1080 =item * L<HTML::Seamstress>
1081
1082 An L<HTML::Tree> - based module inspired by
1083 XMLC (L<http://xmlc.enhydra.org>), allowing for dynamic
1084 HTML generation via tree rewriting.
1085
1086 =head1 TODO
1087
1088 =over
1089
1090 =item * highlander2
1091
1092 currently the API expects the subtrees to survive or be pruned to be
1093 identified by id:
1094
1095 $if_then->highlander2([
1096 under10 => sub { $_[0] < 10} ,
1097 under18 => sub { $_[0] < 18} ,
1098 welcome => [
1099 sub { 1 },
1100 sub {
1101 my $branch = shift;
1102 $branch->look_down(id => 'age')->replace_content($age);
1103 }
1104 ]
1105 ],
1106 $age
1107 );
1108
1109 but, it should be more flexible. the C<under10>, and C<under18> are
1110 expected to be ids in the tree... but it is not hard to have a check to
1111 see if this field is an array reference and if it, then to do a look
1112 down instead:
1113
1114 $if_then->highlander2([
1115 [class => 'under10'] => sub { $_[0] < 10} ,
1116 [class => 'under18'] => sub { $_[0] < 18} ,
1117 [class => 'welcome'] => [
1118 sub { 1 },
1119 sub {
1120 my $branch = shift;
1121 $branch->look_down(id => 'age')->replace_content($age);
1122 }
1123 ]
1124 ],
1125 $age
1126 );
1127
1128
1129
1130 =cut
1131
1132 =head1 SEE ALSO
1133
1134 L<HTML::Seamstress>
1135
1136 =head1 AUTHOR / SOURCE
1137
1138 Terrence Brannon, E<lt>tbone@cpan.orgE<gt>
1139
1140 Many thanks to BARBIE for his RT bug report.
1141
1142 The source is at L<http://github.com/metaperl/html-element-library/tree/master>
1143
1144 =head1 COPYRIGHT AND LICENSE
1145
1146 Copyright (C) 2004 by Terrence Brannon
1147
1148 This library is free software; you can redistribute it and/or modify
1149 it under the same terms as Perl itself, either Perl version 5.8.4 or,
1150 at your option, any later version of Perl 5 you may have available.
1151
1152
1153 =cut
This page took 0.059286 seconds and 4 git commands to generate.