Skip to content

Commit

Permalink
Add create_newlines to replace BR and P by 1, resp. 2 newlines (#46)
Browse files Browse the repository at this point in the history
* Add create_newlines to replace BR and P by 1, resp. 2 newlines

Fixes #25.

* fixup! Add create_newlines to replace BR and P by 1, resp. 2 newlines
  • Loading branch information
choroba committed Apr 23, 2023
1 parent ceefd0f commit b1cc5d3
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions .stopwords
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
Axel
bolded
br
Carwyn
Dagfinn
DOCTYPE
Expand Down
18 changes: 18 additions & 0 deletions lib/HTML/Restrict.pm
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ has allow_declaration => (
default => 0,
);

has create_newlines => (
is => 'rw',
isa => Bool,
default => 0,
);

has debug => (
is => 'rw',
isa => Bool,
Expand Down Expand Up @@ -245,6 +251,12 @@ sub _build_parser {
}
$self->_processed( ( $self->_processed || q{} ) . $alt );
}
elsif ( $tagname eq 'br' && $self->create_newlines ) {
$self->_processed( ( $self->_processed || "" ) . "\n" );
}
elsif ( $tagname eq 'p' && $self->create_newlines ) {
$self->_processed( ( $self->_processed || "" ) . "\n\n" );
}
elsif ( any { $_ eq $tagname }
@{ $self->strip_enclosed_content } ) {
print "adding $tagname to strippers" if $self->debug;
Expand Down Expand Up @@ -636,6 +648,12 @@ feature is off by default.
$html = $hr->process( $html );
# $html is now: "<!-- comments! -->foo"
=item * create_newlines => [0|1]
Set the value to true if you'd like to have each br tag replaced by a
newline and every p tag replaced by two newlines. If a tag is
specified in the allowed HTML, it won't be replaced.
=item * replace_img => [0|1|CodeRef]
Set the value to true if you'd like to have img tags replaced with
Expand Down
42 changes: 42 additions & 0 deletions t/create-newlines.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env perl
use strict;
use warnings;

use Test::More;
use HTML::Restrict ();

my $hr = HTML::Restrict->new();

{
my $html = q[Line 1<p>Line 2<br>Line 3];
my $processed = $hr->process($html);
is $processed, 'Line 1Line 2Line 3', 'off by default';
}

$hr->create_newlines(1);

{
my $html = q[
Line 1<br>Line 2<br/>Line 3<br />Line 4
];
my $processed = $hr->process($html);
is $processed, "Line 1\nLine 2\nLine 3\nLine 4",
'replace <br> by a newline';
}

{
my $html = q[
Paragraph 1<p>Paragraph 2<p>Paragraph 3</p><p>Paragraph 4];
my $processed = $hr->process($html);
is $processed, "Paragraph 1\n\nParagraph 2\n\nParagraph 3\n\nParagraph 4",
'replace <p> by 2 newlines';
}

{
my $html = q[Line 1<p>Line 2<br>Line 3];
$hr->set_rules( { p => [] } );
my $processed = $hr->process($html);
is $processed, "Line 1<p>Line 2\nLine 3", 'rules have precedence';
}

done_testing();

0 comments on commit b1cc5d3

Please sign in to comment.