| 1 | package Progressive::Web::Application::Template::Base; | ||
| 2 | use strict; | ||
| 3 | use JSON qw//; | ||
| 4 | our $JSON; | ||
| 5 | BEGIN { $JSON = JSON->new->utf8->pretty(1)->allow_nonref->allow_blessed; } | ||
| 6 | |||
| 7 | sub new { | ||
| 8 | my $self = bless {}, $_[0]; | ||
| 9 | $self->{handle} = $_[0] . '::DATA'; | ||
| 10 | $self->{handle_start} = tell $self->{handle}; | ||
| 11 | $self->{data} = $self->get_data_section(); | ||
| 12 | return $self; | ||
| 13 | } | ||
| 14 | |||
| 15 | sub get_data_section { | ||
| 16 | my $fh = $_[0]->{handle}; | ||
| 17 | my $content = do { local $/; <$fh> } or return; | ||
| 18 | seek $_[0]->{handle}, $_[0]->{handle_start}, 0; # reset for next 'call' to get_data_section | ||
| 19 | $content =~ s/^.*\n__DATA__//s; | ||
| 20 | $content =~ s/\n__END__\n.*$/\n/s; | ||
| 21 | my @data = split /^@@\s+(.+?)\s*\r?\n/m, $content; | ||
| 22 | shift @data; | ||
| 23 | return {@data}; | ||
| 24 | } | ||
| 25 | |||
| 26 | sub render { | ||
| 27 | my $templates = $_[0]->{data}; | ||
| 28 | if ($_[0]->can('required_params')) { | ||
| 29 | for ($_[0]->required_params()) { | ||
| 30 | Carp::croak(sprintf 'Required template param not found %s', $_) | ||
| 31 | unless exists $_[1]->{$_}; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | my $dataReg = join '|', map { quotemeta($_) } keys %{$_[1]}; | ||
| 35 | for my $key (keys %{$templates}) { | ||
| 36 | $templates->{$key} =~ s/\{($dataReg)\}/_encode_json($_[1]->{$1})/eg; | ||
| 37 | $templates->{$key} =~ s/\s*$//; | ||
| 38 | } | ||
| 39 | return $templates; | ||
| 40 | } | ||
| 41 | |||
| 42 | sub _encode_json { | ||
| 43 | my $val = $JSON->encode($_[0]); | ||
| 44 | chomp($val); | ||
| 45 | return $val; | ||
| 46 | } | ||
| 47 | |||
| 48 | 1; | ||
| 49 | |||
| 50 | __END__ |