Skip to content

Instantly share code, notes, and snippets.

@jberger
Last active December 17, 2020 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberger/18990fc4d2197ce1ce61edb88e2ed6fa to your computer and use it in GitHub Desktop.
Save jberger/18990fc4d2197ce1ce61edb88e2ed6fa to your computer and use it in GitHub Desktop.
Post-processing HTML with Mojo::DOM (in Dancer2)
use Dancer2;
set views => '.';
any '/' => sub {
template 'welcome';
};
any '/toyshop' => sub {
template 'toyshop';
};
sub https {
my $dom = shift;
$dom->find('a[href^="http:"]')
->each(sub{ $_->{href} =~ s/^http/https/ });
}
sub footer {
my $dom = shift;
my $footer = $dom->at('body footer');
# no footer found, build one just before </body>
unless ($footer) {
$dom->at('body')->append_content($dom->new_tag('footer'));
$footer = $dom->at('body footer');
}
my $wish = $dom->new_tag(p => id => 'wish' => 'Wishing you a happier 2021!');
$footer->append_content($wish);
}
hook after => sub {
require Mojo::DOM;
my $dom = Mojo::DOM->new(response->content);
https($dom);
footer($dom);
response->content("$dom");
};
start;
requires 'Dancer2';
requires 'Mojolicious';
requires 'Test::Mojo::Role::PSGI';
use Mojo::Base -strict;
use Test::More;
use Test::Mojo;
my $t = Test::Mojo->with_roles('+PSGI')->new('app.psgi');
$t->get_ok('/')
->status_is(200)
->text_like('html body h1' => qr|welcome|i)
->attr_is('#list' => href => '/list')
->attr_is('#check' => href => '/check')
->attr_like('#mrsclaus' => href => qr|^https:|)
->element_exists_not('[href^="http:"]');
done_testing;
<html>
<head>
<title>Preview Next Year's Toys!</title>
</head>
<body>
<h1>Preview Next Year's Toys!</h1>
<ul><li>...</li></ul>
<footer>
<p>Made with love by Elves!</p>
</footer>
</body>
</html>
<html>
<head>
<title>Welcome to Santa's Workshop Online!</title>
</head>
<body>
<h1>Welcome to Santa's Workshop Online!</h1>
This is the place to <a id="check" href="/check">your naughty/nice status</a> or send me <a id="list" href="/list">your list</a>.
If you would like to request some of Mrs. Claus' famous homemade candies, please visit her at <a id="mrsclaus" href="http://mrsclaus.example.org">her site</a>.
...
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment