Created
August 7, 2010 16:07
-
-
Save xaicron/512931 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Text::Xslate; | |
use HTML::Entities qw/encode_entities/; | |
use String::Random qw/random_string/; | |
binmode STDOUT => ':utf8'; | |
my $START_TAG = quotemeta '<[:'; | |
my $END_TAG = quotemeta ':]>'; | |
$String::Random::old_patterns{A} = ['A'..'Z', 'a'..'z']; | |
my $tx = Text::Xslate->new( | |
cache => 0, | |
); | |
my $file = shift || die 'Usage: footnote.pl html_file'; | |
main: { | |
my $html = slurp($file); | |
my $notes = collect_note($html); | |
print $html, "\n"; | |
print footnote_html($notes); | |
} | |
sub collect_note { | |
my $html = \$_[0]; | |
my $footnotes = []; | |
my $count = 1; | |
my $prefix; | |
while ( | |
$$html =~ s|$START_TAG ( (?:(?!$END_TAG).)* ) $END_TAG| | |
$prefix = random_string('A' x 10); | |
sprintf '<span class="footnote"><a title="%s" name="%s_fn%d" href="#%2$s_f%3$d">*%3$d</a></span>', | |
encode_entities($1, '<>&"'), $prefix, $count++, | |
|xmse | |
) { | |
my $note = $1; | |
push @$footnotes, +{ | |
note => $note, | |
prefix => $prefix, | |
}; | |
} | |
return $footnotes; | |
} | |
sub footnote_html { | |
my $notes = shift; | |
my $tmpl = slurp(\*DATA); | |
$tx->render_string($tmpl, +{ notes => $notes }); | |
} | |
sub slurp { | |
my $file = shift; | |
my $data; | |
local $/; | |
if (ref $file eq 'GLOB') { | |
$data = <$file>; | |
} | |
else { | |
open my $fh, '<:utf8', $file or die $!; | |
$data = <$fh>; | |
close $fh; | |
} | |
return $data; | |
} | |
__DATA__ | |
<div class="footnote"> | |
<ul> | |
: for $notes -> $note { | |
<li><a name="<: $note.prefix :>_f<: $~note.count :>" href="#<: $note.prefix :>_fn<: $~note.count :>">*<: $~note.count :></a> : <: $note.note | mark_raw :></li> | |
: } | |
</ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment