HTML::...ibrary(3pm)

πŸ“¦
version 5.220000 Β· 2 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’… HTML::Element::Library πŸ’…

okay so bestie, welcome to HTML::Element::Library(3pm) β€” yeah it lives in the User Contributed Perl Documentation part of the manual, and it's genuinely one of those pages that gives you main character energy for working with HTML trees. sit down, get comfy, we're doing this together πŸ’–


🌸 NAME 🌸

HTML::Element::Library β€” HTML::Element convenience functions


✨ SYNOPSIS ✨

use HTML::Element::Library;
use HTML::TreeBuilder;

πŸ¦‹ DESCRIPTION πŸ¦‹

HTML:::Element::Library provides extra methods for HTML::Element.

that's it. that's the whole description. short queen, no notes 🫢


πŸ‘‘ METHODS πŸ‘‘

πŸŽ€ Aliases πŸŽ€

these are little short aliases for the stuff you'd otherwise be typing over and over, and honestly? obsessed. they save you so much wrist pain.

  • $el->fid($id) β€” finds you an element when you hand it the id. literally exactly the same as doing $el->look_down(id => $id), just shorter and cuter.
  • $el->fclass($class) β€” finds one or more elements when you give it one of their classes. it's the same as $el->look_down(class => qr/\b$class\b/s), no cap.

🌈 Positional Querying Methods 🌈

these ones are all about where an element is sitting in the tree. it's giving "map coordinates but for HTML" πŸ—ΊοΈ

  • $elem->siblings β€” hands you back a list of every single node chillin' under the same parent.
  • $elem->sibdex β€” gives you the index of $elem inside the array of siblings it's part of. fun fact: HTML::ElementSuper calls this method addr, but our author is like "ngl that name isn't descriptive at all" β€” and also it's deceptively close to the address function of HTML::Element. HOWEVER, for backwards compatibility reasons, both methods are available. so use whichever, bestie, they're both here.
  • $elem->addr β€” same as sibdex. that's it, that's the whole method πŸ’€
  • $elem->position() β€” returns the coordinates of this element in the tree it inhabits. the way it does this is by successively calling addr() on ancestor elements until either a) it hits an element that doesn't support these methods, or b) there are no more parents left. what you get back is the n-dimensional coordinates of that element in the tree. iconic behavior honestly.

🧚 Element Decoration Methods 🧚

  • HTML::Element::Library::super_literal($text) β€” okay so in HTML::Element, Sean Burke talks about super-literals. they're text that does not get escaped. great for including Javascript in your HTML, and also great for including foreign language into a document. 🌍

so basically you toss super_literal your text and back comes your text wrapped in a ~literal element. cute right?

one of these days, the author says, they'll get around to writing a nice EXPORT section. we're waiting respectfully πŸ™ˆ


πŸ”₯ Tree Rewriting Methods πŸ”₯

"de-prepping" HTML

okay so oftentimes the HTML you're working with is gonna have a bunch of sample rows, like this:

<OL>
 <LI>bread
 <LI>butter
 <LI>beer
 <LI>bacon
</OL>

but before you start rewriting the HTML with your actual model data, you typically only want like 1 or 2 sample rows. so you want to "crunch" those multiple sample rows down to a specified amount. hence, the crunch method:

$tree->crunch(look_down => [ '_tag' => 'li' ], leave => 2) ;

the leave argument defaults to 1 if you don't give it one. the call up there would "crunch" those 4 sample rows down to:

<OL>
 <LI>bread
 <LI>butter
</OL>

periodt. πŸ’…

Simplifying calls to HTML::FillInForm

so HTML::FillInForm gets and returns strings, which means using HTML::Element instances with it becomes so tedious:

   1. Seamstress has an HTML tree that it wants the form filled in on
   2. Seamstress converts this tree to a string
   3. FillInForm parses the string into an HTML tree and then fills in the form
   4. FillInForm converts the HTML tree to a string
   5. Seamstress re-parses the HTML for additional processing

the author filed a bug about this, right here: <https://rt.cpan.org/Ticket/Display.html?id=44105>

so this function, fillinform, lets you pass a tree to fillinform (along with your data structure) and get a tree back:

my $new_tree = $html_tree->fillinform($data_structure);

Mapping a hashref to HTML elements

it's super super common to get a hashref of data from some external source β€” flat file, database, XML, etc. so having a convenient way to map that data onto HTML? essential, honestly.

turns out there are 3 ways to do this in HTML::Element::Library. the most strict and structured way is with content_handler. the two other methods, hashmap and datamap, require less manual mapping and might prove even more easy to use in certain cases. πŸ‘€

as is usual with Perl, a practical example is always best. so let's take some sample HTML:

<h1>user data</h1>
<span id="name">?</span>
<span id="email">?</span>
<span id="gender">?</span>

now let's say our data structure is this:

$ref = { email => 'jim@beam.com', gender => 'lots' } ;

and let's start with the most strict way to get what you want:

$tree->content_handler(email => $ref->{email} , gender => $ref->{gender}) ;

in this case you manually state the mapping between id tags and hashref keys, and then content_handler retrieves the hashref data and pops it in the specified place. very demure, very mindful. ✨

now let's look at the two (actually 2 and a half) other hash-mapping methods.

$tree->hashmap(id => $ref);

now, what this function does is super-destructive. 😭 it finds every element in the tree with an attribute named id (and since id is a parameter, it could find every element with some other attribute too) and replaces the content of those elements with the hashref value.

so in the case above, the

   <span id="name">?</span>

would come out as

<span id="name"></span>

(it would be blank) β€” because there's nothing in the hash with that value, so it substituted

$ref->{name}

which was blank, and that emptied the contents. rip to your content πŸͺ¦

now let's assume we want to protect name from being auto-assigned. here's what you do:

$tree->hashmap(id => $ref, ['name']);

that last array ref is an exclusion list. πŸ›‘οΈ

but wouldn't it be nice if you could do a hashmap, but only assign things which are defined in the hashref? defmap() to the rescue:

$tree->defmap(id => $ref);

does just that, so

   <span id="name">?</span>

would be left alone. she's protected, she's safe, she's thriving 🌸

  • $elem->hashmap($attr_name, \%hashref, \@excluded, $debug) β€” this method is designed to take a hashref and populate a series of elements. for example:
<table>
  <tr sclass="tr" class="alt" align="left" valign="top">
    <td smap="people_id">1</td>
    <td smap="phone">(877) 255-3239</td>
    <td smap="password">*********</td>
  </tr>
</table>

in the table above there are several attributes named smap. if we have a hashref whose keys are the same:

my %data = (people_id => 888, phone => '444-4444', password => 'dont-you-dare-render');

then a single API call lets us populate the HTML while excluding the ones we don't want:

$tree->hashmap(smap => \%data, ['password']);

note: the other way to prevent rendering some of the hash mapping is to simply not give that element the attr you plan to use for hash mapping. sneaky but valid.

also note: the function hashmap has a simple easy-to-type API. internally, it calls hash_map (which has a more verbose keyword calling API). so the above call to hashmap() results in this call:

$tree->hash_map(hash => \%data, to_attr => 'sid', excluding => ['password']);
  • $elem->defmap($attr_name, \%hashref, $debug) β€” defmap was described above. go scroll back up bestie, it's right there 🫢
  • $elem->replace_content(@new_elem) β€” replaces all of $elem's content with @new_elem. out with the old, in with the new.
  • $elem->wrap_content($wrapper_element) β€” wraps the existing content in the provided element. but if the provided element happens to be a non-element, a push_content is performed instead. plot twist πŸŒͺ️
  • $elem->set_child_content(@look_down, $content) β€” this method looks down $tree using the criteria specified in @look_down, using the the HTML::Element look_down() method. after finding the node, it detaches the node's content and pushes $content as the node's content.
  • $tree->content_handler(%id_content) β€” this is a convenience method. because the look_down criteria will often simply be:
id => 'fixme'

to find things like:

<a id=fixme href=http://www.somesite.org>replace_content</a>

you can call this method to shorten your typing a bit. so you can simply type

$elem->content_handler( fixme => 'new text' )

instead of typing:

$elem->set_child_content(sid => 'fixme', 'new text')

ALSO NOTE: you can pass a hash whose keys are ids and whose values are the content you want there, and it will perform the replacement on each hash member:

my %id_content = (name => "Terrence Brannon",
                  email => 'tbrannon@in.com',
                  balance => 666,
                  content => $main_content);
$tree->content_handler(%id_content);
  • $tree->highlander($subtree_span_id, $conditionals, @conditionals_args) β€” this one allows for if-then-else style processing. Highlander was a movie in which only one would survive. well, in terms of a tree, when you're looking at a structure you want to process in if-then-else style, only one child will survive. βš”οΈ for example, given this HTML template:
<span klass="highlander" id="age_dialog">
   <span id="under10">
      Hello, does your mother know you're
      using her AOL account?
   </span>
   <span id="under18">
      Sorry, you're not old enough to enter
      (and too dumb to lie about your age)
   </span>
   <span id="welcome">
      Welcome
   </span>
</span>

we only want one child of the span tag with id age_dialog to remain, based on the age of the person visiting the page.

so let's set up a call that will prune the subtree as a function of age:

sub process_page {
 my $age = shift;
 my $tree = HTML::TreeBuilder->new_from_file('t/html/highlander.html');

 $tree->highlander
   (age_dialog =>
    [
     under10 => sub { $_[0] < 10},
     under18 => sub { $_[0] < 18},
     welcome => sub { 1 }
    ],
    $age
   );

and there we have it. if the age is less than 10, then the node with id under10 remains. for age less than 18, the node with id under18 remains. otherwise our else condition fires and the child with id welcome remains. there can be only one πŸ‘‘

  • $tree->passover(@id_of_element) β€” in some cases you know exactly which element(s) should survive. in that case you can simply call passover to remove its (their) siblings. for the HTML above, you could delete under10 and welcome by simply calling:
$tree->passover('under18');

and because passover takes an array, you can specify several children to preserve. multi-select but make it preservation πŸŽ€

  • $tree->highlander2($tree, $conditionals, @conditionals_args) β€” right around the same time that table2() came into being, Seamstress began to tackle tougher and tougher processing problems. it became clear that a more powerful highlander was needed... one that not only snipped the tree of the nodes that should not survive, but one that allows for post-processing of the survivor node. and one that was more flexible with how to find the nodes to snip.

thus (drum roll) highlander2(). πŸ₯

so let's look at our HTML which requires post-selection processing:

   <span klass="highlander" id="age_dialog">
      <span id="under10">
         Hello, little <span id=age>AGE</span>-year old,
      does your mother know you're using her AOL account?
      </span>
      <span id="under18">
         Sorry, you're only <span id=age>AGE</span>
         (and too dumb to lie about your age)
      </span>
      <span id="welcome">
         Welcome, isn't it good to be <span id=age>AGE</span> years old?
      </span>
   </span>

so in this case a branch survives, but it's just sitting there with dummy data in it 😭. We have to take that surviving segment of HTML and rewrite the age span with the actual age. And here is how we use highlander2() to do exactly that:

sub replace_age {
  my $branch = shift;
  my $age = shift;
  $branch->look_down(id => 'age')->replace_content($age);
}

my $if_then = $tree->look_down(id => 'age_dialog');

$if_then->highlander2(
  cond => [
    under10 => [
      sub { $_[0] < 10} ,
      \&replace_age
     ],
    under18 => [
      sub { $_[0] < 18} ,
      \&replace_age
     ],
    welcome => [
      sub { 1 },
      \&replace_age
     ]
   ],
  cond_arg => [ $age ]
);

We pass it the tree ($if_then), an arrayref of conditions (cond) and an arrayref of arguments that get handed to the conds and to the replacement subs. Delegation? Obsessed. πŸ’…

The under10, under18 and welcome are id attributes in the tree of the siblings, and only one of them is gonna survive. But bestie β€” if you need to do some more complex look-downs to find that survivor, then you just supply an array ref instead of a plain scalar:

$if_then->highlander2(
  cond => [
    [class => 'r12'] => [
      sub { $_[0] < 10} ,
      \&replace_age
     ],
    [class => 'z22'] => [
      sub { $_[0] < 18} ,
      \&replace_age
     ],
    [class => 'w88'] => [
      sub { 1 },
      \&replace_age
     ]
   ],
  cond_arg => [ $age ]
);

🌸 $tree->overwrite_attr($mutation_attr => $mutating_closures) 🌸

This method is literally designed for taking a tree and reworking a set of nodes in a stereotyped fashion. For instance, let's say you have 3 remote image archives, but you are not about to put long URLs in your img src tags β€” for reasons of abstraction, re-use and brevity, obviously. So instead you do this:

<img src="/img/smiley-face.jpg" fixup="src lnc">
<img src="/img/hot-babe.jpg"    fixup="src playboy">
<img src="/img/footer.jpg"      fixup="src foobar">

and then when the tree of HTML is being processed, you make this call:

my %closures = (
   lnc     => sub { my ($tree, $mute_node, $attr_value)= @_; "http://lnc.usc.edu$attr_value" },
   playboy => sub { my ($tree, $mute_node, $attr_value)= @_; "http://playboy.com$attr_value" }
   foobar  => sub { my ($tree, $mute_node, $attr_value)= @_; "http://foobar.info$attr_value" }
)

$tree->overwrite_attr(fixup => \%closures) ;

and the tags come out modified like so:

<img src="http://lnc.usc.edu/img/smiley-face.jpg" fixup="src lnc">
<img src="http://playboy.com/img/hot-babe.jpg"    fixup="src playboy">
<img src="http://foobar.info/img/footer.jpg"      fixup="src foobar">

πŸ¦‹ $tree->mute_elem($mutation_attr => $mutating_closures, [ $post_hook ] ) πŸ¦‹

This is a generalization of overwrite_attr, okay? overwrite_attr assumes the return value of the closure is supposed to overwrite an attribute value, and it does that for you. mute_elem is the more general function: it does nothing but hand the closure the element and let it mutate it as it jolly well pleases :)

In fact, here is the implementation of overwrite_attr, so you can get a little taste of how mute_attr is used:

sub overwrite_action {
  my ($mute_node, %X) = @_;

  $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
}

sub HTML::Element::overwrite_attr {
  my $tree = shift;

  $tree->mute_elem(@_, \&overwrite_action);
}

🌳 Tree-Building Methods 🌳

πŸ’– Unrolling an array via a single sample element (<ul> container)

This is best described by example, so here's the example. Given this HTML:

<strong>Here are the things I need from the store:</strong>
<ul>
  <li class="store_items">Sample item</li>
</ul>

We can unroll it like so:

my $li = $tree->look_down(class => 'store_items');

my @items = qw(bread butter vodka);

$tree->iter($li => @items);

To produce this:

<html>
 <head></head>
 <body>Here are the things I need from the store:
   <ul>
     <li class="store_items">bread</li>
     <li class="store_items">butter</li>
     <li class="store_items">vodka</li>
   </ul>
 </body>
</html>

Now you might be wondering why the API call is:

$tree->iter($li => @items)

instead of:

$li->iter(@items)

and there is no good answer πŸ’€. The latter would be more concise and it is what I should have done. Not me admitting that in the docs but here we are πŸ™ˆ.

🧚 Unrolling an array via a single sample element and a callback (<ul> container)

This is the more advanced version of the previous method. Instead of cloning the sample element several times and calling replace_content on the clone with the array element, a custom callback is called with the clone and the array element.

Here is the example from before.

<strong>Here are the things I need from the store:</strong>
<ul>
  <li class="store_items">Sample item</li>
</ul>

Code:

sub cb {
  my ($data, $li) = @_;
  $li->replace_content($data);
}

my $li = $tree->look_down(class => 'store_items');
my @items = qw(bread butter vodka);
$li->itercb(\@items, \&cb);

Output is as before:

<html>
 <head></head>
 <body>Here are the things I need from the store:
   <ul>
     <li class="store_items">bread</li>
     <li class="store_items">butter</li>
     <li class="store_items">vodka</li>
   </ul>
 </body>
</html>

Here is a more complex example (unrolling a table). HTML:

<table><thead><th>First Name<th>Last Name<th>Option</thead>
<tbody>
<tr><td class="first">First<td class="last">Last<td class="option">1
</tbody></table>

Code:

sub tr_cb {
  my ($data, $tr) = @_;
  $tr->look_down(class => 'first')->replace_content($data->{first});
  $tr->look_down(class => 'last')->replace_content($data->{last});
  $tr->look_down(class => 'option')->replace_content($data->{option});
}

my @data = (
  {first => 'Foo', last => 'Bar', option => 2},
  {first => 'Bar', last => 'Bar', option => 3},
  {first => 'Baz', last => 'Bar', option => 4},
);

my $tr = $tree->find('table')->find('tbody')->find('tr');
$tr->itercb(\@data, \&tr_cb);

Produces:

<table><thead><th>First Name<th>Last Name<th>Option</thead>
<tbody>
<tr><td class="first">Foo<td class="last">Bar<td class="option">2
<tr><td class="first">Bar<td class="last">Bar<td class="option">3
<tr><td class="first">Baz<td class="last">Bar<td class="option">4
</tbody></table>

🌈 Unrolling an array via n sample elements (<dl> container)

iter() was fine for awhile, but some things (e.g. definition lists) need a more general function to make them easy to do. Hence iter2(), bestie. This function is gonna be explained by example β€” unrolling a simple definition list.

So here's our mock-up HTML from the designer:

<dl class="dual_iter" id="service_plan">
  <dt>Artist</dt>
  <dd>A person who draws blood.</dd>

  <dt>Musician</dt>
  <dd>A clone of Iggy Pop.</dd>

  <dt>Poet</dt>
  <dd>A relative of Edgar Allan Poe.</dd>

  <dt class="adstyle">sample header</dt>
  <dd class="adstyle2">sample data</dd>
</dl>

And we want to unroll our data set:

my @items = (
  ['the pros'   => 'never have to worry about service again'],
  ['the cons'   => 'upfront extra charge on purchase'],
  ['our choice' => 'go with the extended service plan']
);

Now let's make this problem a bit harder, to show off the power of iter2(). Let's assume we want only the last <dt> and its accompanying <dd> (the one with sample data) to be used as the sample data for unrolling with our data set. And let's further assume we want them to remain in the final output. Periodt.

So now the API to iter2() gets discussed, and we'll explain how our goal of getting our data into HTML fits into that API. 🫢

  • wrapper_ld β€” This is how to look down and find the container of all the elements we're gonna unroll. The <dl> tag is the container for the dt and dd tags we're unrolling.

If you pass an anonymous subroutine, then it's presumed that executing that subroutine will return the HTML::Element representing the container tag. If you pass an array ref, then it gets dereferenced and passed to HTML::Element::look_down().

default value: ['_tag' => 'dl']

Based on the mock HTML above, this default is fine for finding our container tag. So let's move on. ✨

  • wrapper_data β€” This is an array reference of data that we'll be putting into the container. You must supply this. @items above is our wrapper_data.
  • wrapper_proc β€” After we find the container via wrapper_ld, we may want to pre-process some aspect of this tree. In our case the first two sets of dt and dd need to be removed, leaving the last dt and dd. So we supply a wrapper_proc which will do this.

default: undef

  • item_ld β€” This anonymous subroutine returns an array ref of HTML::Elements that will be cloned and populated with item data (item data is a "row" of wrapper_data).

default: returns an arrayref consisting of the dt and dd element inside the container.

  • item_data β€” This is a subroutine that takes wrapper_data and retrieves one "row" to be "pasted" into the array ref of HTML::Elements found via item_ld. I hope that makes sense πŸ’œ.

default: shifts wrapper_data.

  • item_proc β€” This is a subroutine that takes the item_data and the HTML::Elements found via item_ld and produces an arrayref of HTML::Elements which will eventually be spliced into the container.

Note that this subroutine MUST return the new items. This is done so that more items than were passed in can be returned. This is useful when, for example, you must return 2 dts for an input data item. And when would you do this? When a single term has multiple spellings for instance.

default: expects item_data to be an arrayref of two elements and item_elems to be an arrayref of two HTML::Elements. It replaces the content of the HTML::Elements with the item_data.

  • splice β€” okay so once we've built up that whole array of @item_elems, the sub you hand over as splice gets the parent container HTML::Element plus the @item_elems. And what happens next is entirely up to your routine: it could put, like, half of them in. It could unshift them. Whatever. Your call, bestie.

default: $container->splice_content(0, 2, @item_elems) β€” in other words, yeet the 2 sample elements and replace them with the freshly generated @item_elems.

So now that we've documented the API, let's look at the call we actually need:

$tree->iter2(
 # default wrapper_ld ok.
 wrapper_data => \@items,
 wrapper_proc => sub {
   my ($container) = @_;

   # only keep the last 2 dts and dds
   my @content_list = $container->content_list;
   $container->splice_content(0, @content_list - 2);
 },

 # default item_ld is fine.
 # default item_data is fine.
 # default item_proc is fine.
 splice       => sub {
   my ($container, @item_elems) = @_;
   $container->unshift_content(@item_elems);
 },
 debug => 1,
);

✨ Select Unrolling ✨

The unroll_select method has this API, bestie, write it down:

$tree->unroll_select(
   select_label    => $id_label,
   option_value    => $closure, # how to get option value from data row
   option_content  => $closure, # how to get option content from data row
   option_selected => $closure, # boolean to decide if SELECTED
   data            => $data     # the data to be put into the SELECT
   data_iter       => $closure  # the thing that will get a row of data
   debug           => $boolean,
   append          => $boolean, # remove the sample <OPTION> data or append?
);

Here's an example, because examples are everything:

$tree->unroll_select(
  select_label     => 'clan_list',
  option_value     => sub { my $row = shift; $row->clan_id },
  option_content   => sub { my $row = shift; $row->clan_name },
  option_selected  => sub { my $row = shift; $row->selected },
  data             => \@query_results,
  data_iter        => sub { my $data = shift; $data->next },
  append => 0,
  debug => 0
);

πŸŽ€ Tree-Building Methods: Table Generation πŸŽ€

Matthew Sisk has a much more intuitive (imperative, no cap) way to generate tables via his module HTML::ElementTable.

But for those of us with callback fever πŸ’…, the following method is available. First we look at a nuts-and-bolts way to build a table using only the standard HTML::Tree API calls. Then the table method available here gets discussed.

🌸 Sample Model 🌸

package Simple::Class;

use Set::Array;

my @name   = qw(bob bill brian babette bobo bix);
my @age    = qw(99  12   44    52      12   43);
my @weight = qw(99  52   80   124     120  230);

sub new {
  my $this = shift;
  bless {}, ref($this) || $this;
}

sub load_data {
  my @data;

  for (0 .. 5) {
    push @data, {
      age    => $age[rand $#age] + int rand 20,
      name   => shift @name,
      weight => $weight[rand $#weight] + int rand 40
    }
  }

  Set::Array->new(@data);
}

1;

⭐ Sample Usage ⭐

my $data = Simple::Class->load_data;
++$_->{age} for @$data

πŸ¦‹ Inline Code to Unroll a Table πŸ¦‹

HTML:

<html>
  <table id="load_data">
    <tr>  <th>name</th><th>age</th><th>weight</th> </tr>
    <tr id="iterate">
        <td id="name">   NATURE BOY RIC FLAIR  </td>
        <td id="age">    35                    </td>
        <td id="weight"> 220                   </td>
    </tr>
  </table>
</html>

The manual way (NOT recommended, fr fr):

require 'simple-class.pl';
use HTML::Seamstress;

# load the view
my $seamstress = HTML::Seamstress->new_from_file('simple.html');

# load the model
my $o = Simple::Class->new;
my $data = $o->load_data;

# find the <table> and <tr>
my $table_node = $seamstress->look_down('id', 'load_data');
my $iter_node  = $table_node->look_down('id', 'iterate');
my $table_parent = $table_node->parent;

# drop the sample <table> and <tr> from the HTML
# only add them in if there is data in the model
# this is achieved via the $add_table flag

$table_node->detach;
$iter_node->detach;
my $add_table;

# Get a row of model data
while (my $row = shift @$data) {

  # We got row data. Set the flag indicating ok to hook the table into the HTML
  ++$add_table;

  # clone the sample <tr>
  my $new_iter_node = $iter_node->clone;

  # find the tags labeled name age and weight and
  # set their content to the row data
  $new_iter_node->content_handler($_ => $row->{$_})
   for qw(name age weight);

  $table_node->push_content($new_iter_node);

}

# reattach the table to the HTML tree if we loaded data into some table rows

$table_parent->push_content($table_node) if $add_table;

print $seamstress->as_HTML;

$tree->table() : the API call to unroll a table 🫢

require 'simple-class.pl';
use HTML::Seamstress;

# load the view
my $seamstress = HTML::Seamstress->new_from_file('simple.html');
# load the model
my $o = Simple::Class->new;

$seamstress->table
  (
   # tell seamstress where to find the table, via the method call
   # ->look_down('id', $gi_table). Seamstress detaches the table from the
   # HTML tree automatically if no table rows can be built

     gi_table    => 'load_data',

   # tell seamstress where to find the tr. This is a bit useless as
   # the <tr> usually can be found as the first child of the parent

     gi_tr       => 'iterate',

   # the model data to be pushed into the table

     table_data  => $o->load_data,

   # the way to take the model data and obtain one row
   # if the table data were a hashref, we would do:
   # my $key = (keys %$data)[0]; my $val = $data->{$key}; delete $data->{$key}

     tr_data     => sub {
       my ($self, $data) = @_;
       shift @{$data} ;
     },

   # the way to take a row of data and fill the <td> tags

     td_data     => sub {
       my ($tr_node, $tr_data) = @_;
       $tr_node->content_handler($_ => $tr_data->{$_})
      for qw(name age weight)
     }
  );

print $seamstress->as_HTML;

πŸ’œ Looping over Multiple Sample Rows πŸ’œ

  • HTML:
<html>
  <table id="load_data" CELLPADDING=8 BORDER=2>
  <tr>  <th>name</th><th>age</th><th>weight</th> </tr>
  <tr id="iterate1" BGCOLOR="white" >
    <td id="name">   NATURE BOY RIC FLAIR  </td>
    <td id="age">    35                    </td>
    <td id="weight"> 220                   </td>
  </tr>
  <tr id="iterate2" BGCOLOR="#CCCC99">
    <td id="name">   NATURE BOY RIC FLAIR  </td>
    <td id="age">    35                    </td>
    <td id="weight"> 220                   </td>
  </tr>
</table>
</html>
  • Only one change to the last API call.

This:

gi_tr       => 'iterate',

becomes this:

gi_tr       => ['iterate1', 'iterate2']

πŸ‘‘ $tree->table2() : New API Call to Unroll a Table πŸ‘‘

So after like 2 or 3 years of living with table(), I started building production websites with it and decided it needed a cleaner interface β€” especially around handling the fact that id tags are gonna be the same after you clone a table row. πŸ™ˆ

First, here's a dry listing of the function's argument parameters. Honestly this probably isn't the educational part. A better way to get how to use the function is to read the incremental unrolling of its interface given in conversational style after the dry listing. But take your pick, bestie β€” it's the same information, two different ways. ✨

Dry/technical parameter documentation

$tree->table2(%param) takes the following arguments:

  • table_ld => $look_down : optional

How to find the table element in $tree. If $look_down is an arrayref, then use look_down. If it is a CODE ref, then call it, passing it $tree.

Defaults to ['_tag' => 'table'] if not passed in.

  • table_data => $tabular_data : required

The data to fill the table with. Must be passed in.

  • table_proc => $code_ref : not implemented

A subroutine to do something to the table once it is found. Not currently implemented. Not obviously necessary. Just created because there is a tr_proc and td_proc.

  • tr_ld => $look_down : optional

Same as table_ld but for finding the table row elements. Please note that the tr_ld is done on the table node that was found instead of the whole HTML tree. This makes sense. The trs that you want exist below the table that was just found.

Defaults to ['_tag' => 'tr'] if not passed in.

  • tr_data => $code_ref : optional

How to take the table_data and return a row. Defaults to:

sub { my ($self, $data) = @_;
  shift(@{$data}) ;
}
  • tr_proc => $code_ref : optional

Something to do to the table row we are about to add to the table we are making. Defaults to a routine which makes the id attribute unique:

sub {
  my ($self, $tr, $tr_data, $tr_base_id, $row_count) = @_;
  $tr->attr(id => sprintf "%s_%d", $tr_base_id, $row_count);
}
  • td_proc => $code_ref : required

This coderef will take the row of data and operate on the td cells that are children of the tr. See t/table2.t for several usage examples.

Here's a sample one:

sub {
  my ($tr, $data) = @_;
  my @td = $tr->look_down('_tag' => 'td');
  for my $i (0..$#td) {
    $td[$i]->splice_content(0, 1, $data->[$i]);
  }
}

🌈 Conversational parameter documentation 🌈

The first thing you need is a table. So we need a look-down for that. If you don't give one, it defaults to:

['_tag' => 'table']

Like, what is a table even for if there's no data in it?? A vibe with no content, bestie. So you must hand over a scalar that represents your tabular data source. That scalar might be an array reference, a "next"able iterator, or a DBI statement handle. Whatever it is, it needs to be iterable so we can build up rows of table data. These two fields are required, and they're table_ld and table_data respectively (one is how to find the table, the other is the data to display in it, iykyk).

A lil more on table_ld 🫢 β€” if it happens to be a CODE ref, then executing that code ref is presumed to return the HTML::Element representing the table in the HTML tree.

Next up: we get the row or rows that serve as sample "tr" elements by doing a "look_down" from the "table_elem". Normally one sample row is enough to unroll a table, but consider when you've got alternating table rows πŸ‘€ β€” then this API call would need one of each row, so it can cycle through the sample rows as it loops through the data. Alternatively, you could always just use one row and make the necessary changes to that single "tr" row by mutating the element in "tr_proc" (more on that below). The default "tr_ld" is ['_tag' => 'tr'], but you can overwrite it. Note well, bestie: if you overwrite it with a subroutine, then that subroutine is expected to return the HTML::Element(s) which are "tr" element(s). The reason a subroutine might be preferred? Say the HTML designers gave you 8 sample "tr" rows but you only need one prototype row. Then you write a subroutine to splice out the 7 rows you don't need and leave the one sample row remaining, so this API call can clone it and supply it to the "tr_proc" and "td_proc" calls. Iconic delegation honestly πŸ’…


Now, as we move through the table rows with table data, we need to do two different things on each table row:

  • get one row of data from the "table_data" via "tr_data"

The default procedure assumes the "table_data" is an array reference and shifts a row off of it:

sub {
   my ($self, $data) = @_;
   shift @{$data};
}

Your function MUST return undef when there are no more rows to lay out. 🚨

  • take the "tr" element and mutate it via "tr_proc"

The default procedure simply makes the id of the table row unique:

sub {
  my ($self, $tr, $tr_data, $row_count, $root_id) = @_;
  $tr->attr(id => sprintf "%s_%d", $root_id, $row_count);
}

Now that we have our row of data, we call "td_proc" so it can take the data and the "td" cells in this "tr" and process them. This function must be supplied. No skipping, babes.

πŸ₯Ί Whither a Table with No Rows

Often when a table has no rows, we want to display a message indicating this to the view. Use conditional processing to decide what to display:

<span id=no_data>
  <table><tr><td>No Data is Good Data</td></tr></table>
</span>
<span id=load_data>
   <html>
     <table id="load_data">
       <tr>  <th>name</th><th>age</th><th>weight</th> </tr>
       <tr id="iterate">
         <td id="name">   NATURE BOY RIC FLAIR  </td>
         <td id="age">    35                    </td>
         <td id="weight"> 220                   </td>
       </tr>
     </table>
   </html>
</span>

πŸͺ“ Tree-Killing Methods

  • $tree->prune β€” this removes any nodes from the tree which consist of nothing, or nothing but whitespace. See also delete_ignorable_whitespace in HTML::Element.

🌈 Loltree Functions

A loltree is an arrayref consisting of arrayrefs, and it's used by "new_from__lol" in HTML::Element to produce HTML trees. The CPAN distro XML::Element::Tolol creates such XML trees by parsing XML files, analogous to XML::Toolkit. The whole purpose of the functions in this section is to let you manipulate a loltree programmatically. 🧚

These could not be methods, because if you bless a loltree, then HTML::Tree will barf. 🀒 (Truly a vibe check fail.)

HTML::Element::newchild($lol, $parent_label, @newchild)

Given this initial loltree:

my $initial_lol = [ note => [ shopping => [ item => 'sample' ] ] ];

This code:

sub shopping_items {
  my @shopping_items = map { [ item => _ ] } qw(bread butter beans);
  @shopping_items;
}

my $new_lol = HTML::Element::newnode($initial_lol, item => shopping_items());

will replace the single sample with a list of shopping items:

    [
         'note',
         [
           'shopping',
             [
               'item',
               'bread'
             ],
             [
               'item',
               'butter'
             ],
             [
               'item',
               'beans'
             ]

         ]
       ];

Thanks to kcott and the other Perlmonks in this thread: <http://www.perlmonks.org/?node_id=912416> πŸ’–


πŸ‘€ SEE ALSO

HTML::Tree

A perl package for creating and manipulating HTML trees.

HTML::ElementTable

An HTML::Tree - based module which allows for manipulation of HTML trees using cartesian coordinations.

HTML::Seamstress

An HTML::Tree - based module inspired by XMLC (<http://xmlc.enhydra.org>), allowing for dynamic HTML generation via tree rewriting.

Push-style templating systems

A comprehensive cross-language list of push-style templating systems <http://perlmonks.org/?node_id=674225>.


✨ TODO ✨

  • highlander2

currently the API expects the subtrees to survive or be pruned to be identified by id:

$if_then->highlander2([
  under10 => sub { $_[0] < 10} ,
  under18 => sub { $_[0] < 18} ,
  welcome => [
    sub { 1 },
    sub {
      my $branch = shift;
      $branch->look_down(id => 'age')->replace_content($age);
    }
   ]
 ], $age);

but, it should be more flexible. the "under10", and "under18" are expected to be ids in the tree... but it is not hard to have a check to see if this field is an array reference and if it, then to do a look down instead:

$if_then->highlander2([
  [class => 'under10'] => sub { $_[0] < 10} ,
  [class => 'under18'] => sub { $_[0] < 18} ,
  [class => 'welcome'] => [
    sub { 1 },
    sub {
      my $branch = shift;
      $branch->look_down(id => 'age')->replace_content($age);
    }
   ]
 ], $age);

🫢 AUTHOR

Original author Terrence Brannon, <tbone@cpan.org>.

Adopted by Marius Gavrilescu "<marius@ieval.ro>".

I appreciate the feedback from M. David Moussa Leo Keita regarding some issues with the test suite, namely (1) CRLF leading to test breakage in t/crunch.t and (2) using the wrong module in t/prune.t thus not having the right functionality available.

Many thanks to BARBIE for his RT bug report.

Many thanks to perlmonk kcott for his work on array rewriting: <http://www.perlmonks.org/?node_id=912416>. It was crucial in the development of newchild.


Coypright (C) 2014-2016 by Marius Gavrilescu

Copyright (C) 2004-2012 by Terrence Brannon

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.4 or, at your option, any later version of Perl 5 you may have available.


and that's the whole page, bestie!! πŸ’…βœ¨ this lil legend came from perl v5.34.0 and it was dated 2022-06-14 β€” go forth and tree-rewrite, you absolute icon πŸ‘‘πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from