Created
April 27, 2012 13:24
-
-
Save ranguard/2509181 to your computer and use it in GitHub Desktop.
TT role
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
| package CatalystX::Controller::Role::TemplateFromPath; | |
| use MooseX::MethodAttributes::Role; | |
| use namespace::autoclean; | |
| =head1 NAME | |
| CatalystX::Controller::Role::TemplateFromPath | |
| =head1 SYNOPSIS | |
| package MyApp::Controller::Root; | |
| use Moose; | |
| use namespace::autoclean; | |
| BEGIN { extends 'Catalyst::Controller'; } | |
| ... | |
| with 'CatalystX::Controller::Role::TemplateFromPath'; | |
| # now have template_from_path() action on Root controller... | |
| ... | |
| =head1 DESCRIPTION | |
| Moose role to give a Catalyst Controller the C<template_from_path()> method. | |
| This works out the location of the template from the path, and sets the stash | |
| if found, otherwise returns a 404. | |
| =head1 METHODS | |
| =head2 template_from_path | |
| Works out a template file to return from the path. Done both for unhandled | |
| path requests (i.e. those that hit 'default') and for handled requests that | |
| haven't specified a template. | |
| =cut | |
| sub template_from_path : Private { | |
| my ( $self, $c ) = @_; | |
| my $path = $c->req->path; | |
| # Check no dodgy characters in URL (e.g. hacking attempts etc) | |
| my $legal_chars = quotemeta('.-_/'); | |
| if ( $path =~ /\.\./ && $path =~ /[^\w$legal_chars]/ ) { | |
| warn "Dodgy path: '$path' - returning 404" if $c->debug; | |
| $c->res->status(404); | |
| $c->detach(); | |
| } | |
| # add in index.html if we only have a directory name given | |
| $path =~ s{/$}{}; | |
| $path .= '/index.html' | |
| if $path !~ /html$/ | |
| && $path !~ /xml$/ | |
| && $path !~ /txt$/ | |
| && $path !~ /css$/ | |
| && $path !~ /js$/; | |
| $path =~ s{^/}{}; | |
| # if template doesn't exist, return 404 not found | |
| unless ( grep { -f "$_/$path" } @{ $c->view('TT')->include_path } ) { | |
| warn "Template not found: $path" if $c->debug; | |
| $c->res->status(404); | |
| $c->detach(); | |
| } | |
| $c->stash( template => $path ); | |
| } | |
| 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment