Day 20 - Catalyst::Plugin::Flavour

Adding Sweet Flavours to Catalyst Controllers


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

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 ) );


Simple tutorial

Load plugin:

    use Catalyst qw/Flavour/;

Next up is configuration. If you use ConfigLoader, you edit myapp.yml:

      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/ 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.


      <title>This is HTML</title>
      <h1>This is HTML!</h1>


    {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

/action | /action.html

/path/to/ | /path/to/index | /path/to/index.html

/path/to | /path/to.html

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.


Daisuke Murase (typester) <>