| 1 | package Terse::View::Static; | ||
| 2 | |||
| 3 | use base 'Terse::View'; | ||
| 4 | |||
| 5 | sub build_view { | ||
| 6 | my ($self) = @_; | ||
| 7 | $self->static_directory ||= 'root/static'; | ||
| 8 | $self->allowed = 'js|css|png|svg|jpeg|gif|json|html|txt|eot|ttf|woff|woff2'; | ||
| 9 | $self->mime = { | ||
| 10 | js => 'application/javascript', | ||
| 11 | css => 'text/css', | ||
| 12 | png => 'image/png', | ||
| 13 | svg => 'image/svg', | ||
| 14 | jpeg => 'image/jpeg', | ||
| 15 | gif => 'image/gif', | ||
| 16 | json => 'application/json', | ||
| 17 | html => 'text/html', | ||
| 18 | txt => 'text/plain', | ||
| 19 | eot => 'application/vnd.ms-fontobject', | ||
| 20 | ttf => 'application/font-sfnt', | ||
| 21 | woff => 'application/font-woff', | ||
| 22 | woff2 => 'application/font-woff', | ||
| 23 | }; | ||
| 24 | my $path = $0; | ||
| 25 | $path =~ s/[^\/]+$//g; | ||
| 26 | $self->dir = $path . $self->static_directory; | ||
| 27 | return $self; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub render { | ||
| 31 | my ($self, $t, $data) = @_; | ||
| 32 | my $template = $t->captured->[0] !~ m/^1$/ && $t->captured->[0] || $data->template || $t->template || $t->req; | ||
| 33 | $template = 'html/' . $template . '.html' if ($template !~ m/\.[^\.]+$/); | ||
| 34 | my $allowed = $self->allowed; | ||
| 35 | my ($mime) = $template =~ m/($allowed)$/; | ||
| 36 | return $t->logError('Invalid file mime type for file: ' . $template, 500, 1) unless $mime && $self->mime->$mime; | ||
| 37 | my $file = $self->_read_file($self->dir . '/' . $template); | ||
| 38 | $t->logError('File not found: ' . $template, 500, 1) && return unless $file; | ||
| 39 | return ($self->mime->$mime, $file); | ||
| 40 | } | ||
| 41 | |||
| 42 | sub _read_file { | ||
| 43 | my ($self, $file) = @_; | ||
| 44 | return unless -f $file; | ||
| 45 | open my $fh, '<', $file or die "Cannot read html file: $file:" . $@; | ||
| 46 | my $data = do { local $/; <$fh> }; | ||
| 47 | close $fh; | ||
| 48 | return $data; | ||
| 49 | } | ||
| 50 | |||
| 51 | 1; | ||
| 52 | |||
| 53 | =head1 NAME | ||
| 54 | |||
| 55 | Terse::View::Static - Serve static resources view | ||
| 56 | |||
| 57 | =cut | ||
| 58 | |||
| 59 | =head1 VERSION | ||
| 60 | |||
| 61 | Version 0.10 | ||
| 62 | |||
| 63 | =cut | ||
| 64 | |||
| 65 | =head1 SYNOPSIS | ||
| 66 | |||
| 67 | package MyApp::View::Static; | ||
| 68 | |||
| 69 | use base 'Terse::View::Static'; | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | =cut | ||
| 74 | |||
| 75 | =head1 LICENSE AND COPYRIGHT | ||
| 76 | |||
| 77 | L<Terse::Static>. | ||
| 78 | |||
| 79 | =cut |