Catalyst Advent - Day 12 - Catalyst::Plugin::Subrequest

NOTE: This article was written in 2005. Make sure to check the Catalyst Wiki ( for updated information.

Component based sub-requests.

This is actually one of the features we brought over from Maypole. There it was called Maypole::Plugin::Component. Basically, the idea is to set up new request/response objects, and do an internal request, then return the output. It's quite handy for various situations, Simon's example was a shopping portal. I'm frequently using it to render parts of my site that I'm also rendering with ajax, to avoid duplication of code.

It's quite simple in use. You just call $c->subreq('</public/url>'); (or with TT, [% c.subreq('/public/url') %] .) This will localize enough of your request/response object so that it shouldn't affect your current request, set up a new path/uri, and call the Dispatcher to force a full request chain, including begin/end/auto/default and whatever else applies. if you don't like 'subreq', theres an alias as well: 'sub_request'.

You can also set up the stash before the request, as well as pass parameters to the request like a normal form POST by passing optional hashrefs to the subreq method. for example:

	my $text=$c->subreq('/foo',{ bar=>$c->stash->{bar} }, {id=>23});

This will dispatch to whatever handles '/foo', with bar in the stash, and $c->req->param('id') returning 23. After the request, $text will contain whatever's in $c->res->output.

Note, by the way, that the uri path is relative to the application root, and not necessesarily the webserver root.

-- Marcus Ramberg