added new method to transform content
[catagits/HTML-Zoom.git] / lib / HTML / Zoom / FilterBuilder.pm
index 6040288..f9facd3 100644 (file)
@@ -128,6 +128,28 @@ sub transform_attribute {
    };
 }
 
+sub transform_content {
+  my ( $self, $code ) = @_;
+
+  my $replace = $self->replace_content(
+    sub {
+      $self->_stream_from_proto($code->($_));
+    }
+  );
+  sub {
+    my ( $evt, $stream ) = @_;
+
+    my $item_ref = $stream->next;
+    if ( $item_ref->{type} eq 'TEXT' ) {
+      local $_ = $item_ref->{raw};
+      return $replace->($evt, $stream);
+    }
+    else {
+      return $self->_stream_concat($evt, $stream);
+    }
+  };
+}
+
 sub collect {
   my ($self, $options) = @_;
   my ($into, $passthrough, $content, $filter, $flush_before) =
@@ -690,6 +712,20 @@ or another L<HTML::Zoom> object.
       ->select('title, #greeting')
       ->replace_content('Hello world!');
 
+=head2 transform_content
+
+Given a "select" in HTML::Zoom result, transform the content with a code
+reference. This allows you for example to localize your template text
+elements or doing anything else with the node's text content.
+
+    $html_zoom
+      ->select('a')
+      ->transform_content(
+          sub {
+            "please click on: $_"
+          },
+        );
+
 =head2 repeat
 
 For a given selection, repeat over transformations, typically for the purposes