Day 20 - Catalyst::Plugin::Flavour
Adding Sweet Flavours to Catalyst Controllers
Introduction
Have you ever thought about how to handle multiple templates (or views) from one controller?
Plugin::Flavour provides it to you, as "flavour".
If you use Flavour plugin, then a request for
http://example.com/path/to/action.flavour
is handled by /path/to/action
and the "flavour" is stored in
$c->flavour
.
Now you can use multiple views in one controller like this:
$c->forward( $c->view( $c->flavour ) );
MAGIC!
Simple tutorial
Load plugin:
use Catalyst qw/Flavour/;
Next up is configuration. If you use ConfigLoader, you edit myapp.yml:
flavour: default_flavour: html
default_flavour
is used when request url has no flavour part.
The default value is 'html', so you don't have to write it when you
use 'html' as the default_flavour
.
Before we forget, create Catalyst::View::TT. Please run
./script/myapp_create.pl view TT TT
before continuing.
The next step is to write controllers. In this case, I'll have an html and a json flavour.
Controller code:
# MyApp::Controller::Root sub index : Private { my ( $self, $c ) = @_; $c->stash->{template} = 'index.' . $c->flavour; } sub end : ActionClass('RenderView') {}
Then write two templates.
index.html:
<html> <head> <title>This is HTML</title> </head> <body> <h1>This is HTML!</h1> </body> </html>
index.json:
{title:"This is JSON!"}
Well done!
When you run this app in the development server,
http://localhost:3000/index.html shows index.html,
http://localhost:3000/index.json shows index.json,
and http://localhost:3000/ shows index.html (the default flavour)
Path to controller mapping
Here is list of path to controller mapping used by Plugin::Flavour.
/
|/index
|/index.html
-
/index
/action
|/action.html
-
/action
/path/to/
|/path/to/index
|/path/to/index.html
-
/path/to/index
/path/to
|/path/to.html
-
/path/to
The last slash is important! Suggestions and patchs are welcome for this mapping!
Accessors for real path
Plugin::Flavour replace $c->request->uri
and $c->request->path
for tricking the Catalyst dispatcher. It provides additional
accessor $c->request->real_uri
and $c->request->real_path
for the actual uri and path.
AUTHOR
Daisuke Murase (typester) <typester@cpan.org>
COPYRIGHT
Copyright 2006 Daisuke Murase.
This document can be freely redistributed and can be modified and re-distributed under the same conditions as Perl itself.