.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Dancer2::Manual 3pm" .TH Dancer2::Manual 3pm "2014-10-15" "perl v5.20.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Dancer2::Manual \- A gentle introduction to Dancer2 .SH "VERSION" .IX Header "VERSION" version 0.152000 .SH "DESCRIPTION" .IX Header "DESCRIPTION" Dancer2 is a free and open source web application framework written in Perl. .PP It's a complete rewrite of Dancer, based on Moo and using a more robust and extensible fully-OO design. .PP It's designed to be powerful and flexible, but also easy to use \- getting up and running with your web app is trivial, and an ecosystem of adaptors for common template engines, session storage, logging methods and plugins to make common tasks easy mean you can do what you want to do, your way, easily. .SH "INSTALL" .IX Header "INSTALL" Installation of Dancer2 is simple: .PP .Vb 1 \& perl \-MCPAN \-e \*(Aqinstall Dancer2\*(Aq .Ve .PP Thanks to the magic of cpanminus, if you do not have \s-1CPAN\s0.pm configured, or just want a quickfire way to get running, the following should work, at least on Unix-like systems: .PP .Vb 1 \& wget \-O \- http://cpanmin.us | sudo perl \- Dancer2 .Ve .PP (If you don't have root access, omit the 'sudo', and cpanminus will install Dancer2 and prereqs into \f(CW\*(C`~/perl5\*(C'\fR.) .SH "BOOTSTRAPPING A NEW APP" .IX Header "BOOTSTRAPPING A NEW APP" Create a web application using the dancer script: .PP .Vb 1 \& dancer2 \-a MyApp && cd MyApp .Ve .PP And voila\*`! You can now run the web application: .PP .Vb 1 \& bin/app.pl .Ve .PP View the web application at: .PP .Vb 1 \& http://localhost:3000 .Ve .PP Note that as Dancer2 supports the \s-1PSGI\s0 specification, you can also use the \f(CW\*(C`plackup\*(C'\fR tool (provided by Plack) for launching the application: .PP .Vb 1 \& plackup ./bin/app.pl \-p 5000 .Ve .SH "USAGE" .IX Header "USAGE" When Dancer2 is imported to a script, that script becomes a webapp, and at this point, all the script has to do is declare a list of \fBroutes\fR. A route handler is composed by an \s-1HTTP\s0 method, a path pattern and a code block. \f(CW\*(C`strict\*(C'\fR and \f(CW\*(C`warnings\*(C'\fR pragmas are also imported with Dancer2. .PP The code block given to the route handler has to return a string which will be used as the content to render to the client. .PP Routes are defined for a given \s-1HTTP\s0 method. For each method supported, a keyword is exported by the module. .PP The following is an example of a route definition. The route is defined for the method 'get', so only \s-1GET\s0 requests will be honoured by that route: .PP .Vb 2 \& get \*(Aq/hello/:name\*(Aq => sub { \& # do something \& \& return "Hello ".param(\*(Aqname\*(Aq); \& }; .Ve .SS "\s-1HTTP\s0 Methods" .IX Subsection "HTTP Methods" Here are some of the standard \s-1HTTP\s0 methods which you can use to define your route handlers. .IP "\fB\s-1GET\s0\fR The \s-1GET\s0 method retrieves information, and is the most common" 8 .IX Item "GET The GET method retrieves information, and is the most common" \&\s-1GET\s0 requests should be used for typical \*(L"fetch\*(R" requests \- retrieving information. They should not be used for requests which change data on the server or have other effects. .Sp When defining a route handler for the \s-1GET\s0 method, Dancer2 automatically defines a route handler for the \s-1HEAD\s0 method (in order to honour \s-1HEAD\s0 requests for each of your \s-1GET\s0 route handlers). .Sp To define a \s-1GET\s0 action, use the get keyword. .IP "\fB\s-1POST\s0\fR The \s-1POST\s0 method is used to create a resource on the server." 8 .IX Item "POST The POST method is used to create a resource on the server." To define a \s-1POST\s0 action, use the post keyword. .IP "\fB\s-1PUT\s0\fR The \s-1PUT\s0 method is used to replace an existing resource." 8 .IX Item "PUT The PUT method is used to replace an existing resource." To define a \s-1PUT\s0 action, use the put keyword. .Sp a \s-1PUT\s0 request should replace the existing resource with that specified \- for instance \- if you wanted to just update an email address for a user, you'd have to specify all attributes of the user again; to make a partial update, a \s-1PATCH\s0 request is used. .IP "\fB\s-1PATCH\s0\fR The \s-1PATCH\s0 method updates some attributes of an existing resource." 8 .IX Item "PATCH The PATCH method updates some attributes of an existing resource." To define a \s-1PATCH\s0 action, use the patch keyword. .IP "\fB\s-1DELETE\s0\fR The \s-1DELETE\s0 method requests that the origin server delete the resource identified by the Request-URI." 8 .IX Item "DELETE The DELETE method requests that the origin server delete the resource identified by the Request-URI." To define a \s-1DELETE\s0 action, use the del keyword. .PP To define a route for multiple methods you can also use the special keyword \&\fBany\fR. This example illustrates how to define a route for both \s-1GET\s0 and \s-1POST\s0 methods: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP Or even, a route handler that would match any \s-1HTTP\s0 methods: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .SS "Route Handlers" .IX Subsection "Route Handlers" The route action is the code reference declared. It can access parameters through the \f(CW\*(C`params\*(C'\fR keyword, which returns a hashref. This hashref is a merge of the route pattern matches and the request params. .PP You can have more details about how params are built and how to access them in the Dancer2::Core::Request documentation. .PP \fINamed Matching\fR .IX Subsection "Named Matching" .PP A route pattern can contain one or more tokens (a word prefixed with ':'). Each token found in a route pattern is used as a named-pattern match. Any match will be set in the params hashref. .PP .Vb 3 \& get \*(Aq/hello/:name\*(Aq => sub { \& "Hey ".param(\*(Aqname\*(Aq).", welcome here!"; \& }; .Ve .PP Tokens can be optional, for example: .PP .Vb 3 \& get \*(Aq/hello/:name?\*(Aq => sub { \& defined param(\*(Aqname\*(Aq) ? "Hello there ".param(\*(Aqname\*(Aq) : "whoever you are!"; \& }; .Ve .PP \fIWildcards Matching\fR .IX Subsection "Wildcards Matching" .PP A route can contain a wildcard (represented by a \f(CW\*(C`*\*(C'\fR). Each wildcard match will be returned in an arrayref, accessible via the \f(CW\*(C`splat\*(C'\fR keyword. .PP .Vb 4 \& get \*(Aq/download/*.*\*(Aq => sub { \& my ($file, $ext) = splat; \& # do something with $file.$ext here \& }; .Ve .PP \fIRegular Expression Matching\fR .IX Subsection "Regular Expression Matching" .PP A route can be defined with a Perl regular expression. .PP In order to tell Dancer2 to consider the route as a real regexp, the route must be defined explicitly with \f(CW\*(C`qr{}\*(C'\fR, like the following: .PP .Vb 4 \& get qr{/hello/([\ew]+)} => sub { \& my ($name) = splat; \& return "Hello $name"; \& }; .Ve .PP \fIConditional Matching\fR .IX Subsection "Conditional Matching" .PP Routes may include some matching conditions (on the useragent and the hostname at the moment): .PP .Vb 3 \& get \*(Aq/foo\*(Aq, {agent => \*(AqSongbird (\ed\e.\ed)[\ed\e/]*?\*(Aq} => sub { \& \*(Aqfoo method for songbird\*(Aq \& } \& \& get \*(Aq/foo\*(Aq => sub { \& \*(Aqall browsers except songbird\*(Aq \& } .Ve .SS "Prefix" .IX Subsection "Prefix" A prefix can be defined for each route handler, like this: .PP .Vb 1 \& prefix \*(Aq/home\*(Aq; .Ve .PP From here, any route handler is defined to /home/* .PP .Vb 1 \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq .Ve .PP You can unset the prefix value .PP .Vb 2 \& prefix \*(Aq/\*(Aq; # or: prefix undef; \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .PP Alternatively, to prevent you from ever forgetting to undef the prefix, you can use lexical prefix like this: .PP .Vb 3 \& prefix \*(Aq/home\*(Aq => sub { \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq \& }; ## prefix reset to previous value on exit \& \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .SS "Action Skipping" .IX Subsection "Action Skipping" An action can choose not to serve the current request and ask Dancer2 to process the request with the next matching route. .PP This is done with the \fBpass\fR keyword, like in the following example .PP .Vb 4 \& get \*(Aq/say/:word\*(Aq => sub { \& return pass if (params\->{word} =~ /^\ed+$/); \& "I say a word: ".params\->{word}; \& }; \& \& get \*(Aq/say/:number\*(Aq => sub { \& "I say a number: ".params\->{number}; \& }; .Ve .SS "Default Error Pages" .IX Subsection "Default Error Pages" When an error is rendered (the action responded with a status code different than 200), Dancer2 first looks in the public directory for an \s-1HTML\s0 file matching the error code (eg: 500.html or 404.html). .PP If such a file exists, it's used to render the error, otherwise, a default error page will be rendered on the fly. .SS "Execution Errors" .IX Subsection "Execution Errors" When an error occurs during the route execution, Dancer2 will render an error page with the \s-1HTTP\s0 status code 500. .PP It's possible either to display the content of the error message or to hide it with a generic error page. .PP This is a choice left to the end-user and can be set with the \fBshow_errors\fR setting. .PP Note that you can also choose to consider all warnings in your route handlers as errors when the setting \fBwarnings\fR is set to 1. .SH "HOOKS" .IX Header "HOOKS" Hooks are code references (or anonymous subroutines) that are triggered at specific moments during the resolution of a request. .PP Many of them are supported by the core but plugins and engines can also define their own. .SS "Request workflow" .IX Subsection "Request workflow" \&\f(CW\*(C`before\*(C'\fR hooks are evaluated before each request within the context of the request and receives as argument the app (a Dancer2::Core::App object). .PP It's possible to define variables which will be accessible in the action blocks with the keyword \f(CW\*(C`var\*(C'\fR. .PP .Vb 3 \& hook before => sub { \& var note => \*(AqHi there\*(Aq; \& }; \& \& get \*(Aq/foo/*\*(Aq => sub { \& my ($match) = splat; # \*(Aqoversee\*(Aq; \& vars\->{note}; # \*(AqHi there\*(Aq \& }; .Ve .PP For another example, this can be used along with session support to easily give non-logged-in users a login page: .PP .Vb 6 \& hook before => sub { \& if (!session(\*(Aquser\*(Aq) && request\->dispatch_path !~ m{^/login}) { \& # Pass the original path requested along to the handler: \& forward \*(Aq/login\*(Aq, { requested_path => request\->dispatch_path }; \& } \& }; .Ve .PP The request keyword returns the current Dancer2::Core::Request object representing the incoming request. .PP \&\f(CW\*(C`after\*(C'\fR hooks are evaluated after the response has been built by a route handler, and can alter the response itself, just before it's sent to the client. .PP This hook runs after a request has been processed, but before the response is sent. .PP It receives a Dancer2::Core::Response object, which it can modify if it needs to make changes to the response which is about to be sent. .PP The filter is given the response object as its first argument: .PP .Vb 4 \& hook after => sub { \& my $response = shift; \& $response\->(content, \*(Aqafter filter got here!\*(Aq); \& }; .Ve .SS "Templates" .IX Subsection "Templates" \&\f(CW\*(C`before_template_render\*(C'\fR hooks are called whenever a template is going to be processed, they are passed the tokens hash which they can alter. .PP .Vb 4 \& hook before_template_render => sub { \& my $tokens = shift; \& $tokens\->{foo} = \*(Aqbar\*(Aq; \& } .Ve .PP The tokens hash will then be passed to the template with all the modifications performed by the filter. This is a good way to setup some global vars you like to have in all your templates, like the name of the user logged in or a section name. .PP \&\f(CW\*(C`after_template_render\*(C'\fR hooks are called after the view has been rendered. They receive as their first argument the reference to the content that has been produced. This can be used to post-process the content rendered by the template engine. .PP .Vb 6 \& hook after_template_render => sub { \& my $ref_content = shift; \& my $content = $$ref_content; \& # do something with $content \& $ref_content = \e$content; \& }; .Ve .PP \&\f(CW\*(C`before_layout_render\*(C'\fR hooks are called whenever the layout is going to be applied to the current content. The arguments received by the hook are the current tokens hashref and a reference to the current content. .PP .Vb 5 \& hook before_layout_render => sub { \& my ($tokens, $ref_content) = @_; \& $tokens\->{new_stuff} = 42; \& $ref_conent = \e"new content"; \& }; .Ve .PP \&\f(CW\*(C`after_layout_render\*(C'\fR hooks are called once the complete content of the view has been produced, after the layout has been applied to the content. The argument received by the hook is a reference to the complete content string. .PP .Vb 4 \& hook after_layout_render => sub { \& my $ref_content = shift; \& ... \& }; .Ve .SS "Error handling" .IX Subsection "Error handling" When an error is caught by Dancer2's core, an exception object is built (of the class Dancer2::Core::Error). This class provides hook to let the user alter the error work-flow if needed. .PP \&\f(CW\*(C`init_error\*(C'\fR hooks are called whenever an error object is built, the object is passed to the hook. .PP .Vb 4 \& hook init_error => sub { \& my $error = shift; \& # do something with $error \& }; .Ve .PP \&\fIThis hook was named \f(BIbefore_error_init\fI in Dancer, and is now aliased to this hook.\fR .PP \&\f(CW\*(C`before_error\*(C'\fR hooks are called whenever an error is going to be thrown, it receives the error object as its first and unique argument. .PP .Vb 4 \& hook before_error => sub { \& my $error = shift; \& # do something with $error \& }; .Ve .PP \&\fIThis hook was named \f(BIbefore_error_render\fI in Dancer, and is now aliased to this hook.\fR .PP \&\f(CW\*(C`after_error\*(C'\fR hooks are called whenever an error object has been thrown, it receives a Dancer2::Core::Response object as the first argument. .PP .Vb 3 \& hook after_error => sub { \& my $response = shift; \& }; .Ve .PP \&\fIThis hook was named .PP \&\f(CW\*(C`on_route_exception\*(C'\fR is called when an exception has been caught, at the route level, just before rethrowing it higher. This hook receives a Dancer2::Core::App and the error as arguments. .PP .Vb 3 \& hook on_route_exception => sub { \& my ($app, $error) = @_; \& }; .Ve .SS "File rendering" .IX Subsection "File rendering" Whenever a content is produced out of the parsing of a static file, the Dancer2::Handler::File component is used. This component provides two hooks, \f(CW\*(C`before_file_render\*(C'\fR and \f(CW\*(C`after_file_render\*(C'\fR. .PP \&\f(CW\*(C`before_file_render\*(C'\fR hooks are called just before starting to parse the file, the hook receives as its first argument the file path that is going to be processed. .PP .Vb 3 \& hook before_file_render => sub { \& my $path = shift; \& }; .Ve .PP \&\f(CW\*(C`after_file_render\*(C'\fR are called after the file has been parsed and the response content produced. It receives the response object (Dancer2::Core::Response) produced. .PP .Vb 3 \& hook after_file_render => sub { \& my $response = shift; \& }; .Ve .SS "Serializers" .IX Subsection "Serializers" \&\f(CW\*(C`before_serializer\*(C'\fR is called before serializing the content, and receives as argument the content to serialize. .PP .Vb 4 \& hook before_serializer => sub { \& my $content = shift; \& ... \& }; .Ve .PP \&\f(CW\*(C`after_serializer\*(C'\fR is called after the payload was serialized, and receives the serialized content as an argument. .PP .Vb 4 \& hook after_serializer => sub { \& my $content = shift; \& ... \& }; .Ve .SH "CONFIGURATION AND ENVIRONMENTS" .IX Header "CONFIGURATION AND ENVIRONMENTS" Configuring a Dancer2 application can be done in many ways. The easiest one (and maybe the dirtiest) is to put all your settings statements at the top of your script, before calling the \fIdance()\fR method. .PP Other ways are possible. You could write all your setting calls in the file `appdir/config.yml'. You would, of course, have write the conffile in \s-1YAML.\s0 .PP While better than the first option, it's still not perfect. You can't easily switch from an environment to another (for example, from development to production) without rewriting the config.yml file. The best way is to have one config.yml file with default global settings, like the following: .PP .Vb 3 \& # appdir/config.yml \& logger: \*(Aqfile\*(Aq \& layout: \*(Aqmain\*(Aq .Ve .PP And then write as many environment files as you like in appdir/environments. That way, the appropriate environment config file will be loaded according to the running environment (if none is specified, 'development' is assumed). .PP Note that you can change the running environment using the \-\-environment commandline switch. .PP Typically, you'll want to set the following values in a development config file: .PP .Vb 4 \& # appdir/environments/development.yml \& log: \*(Aqdebug\*(Aq \& startup_info: 1 \& show_errors: 1 .Ve .PP And in a production one: .PP .Vb 4 \& # appdir/environments/production.yml \& log: \*(Aqwarning\*(Aq \& startup_info: 0 \& show_errors: 0 .Ve .PP Please note that you are not limited to writing configuration files in \s-1YAML.\s0 Dancer2 supports any file format that is supported by Config::Any, such as \s-1JSON, XML, INI\s0 files, and Apache-style config files. .SS "Accessing configuration data" .IX Subsection "Accessing configuration data" A Dancer2 application can access the information from its config file easily with the config keyword: .PP .Vb 3 \& get \*(Aq/appname\*(Aq => sub { \& return "This is " . config\->{appname}; \& }; .Ve .SS "Settings" .IX Subsection "Settings" It's possible to change quite every parameter of the application via the settings mechanism. .PP A setting is key/value pair assigned by the keyword \fBset\fR: .PP .Vb 1 \& set setting_name => \*(Aqsetting_value\*(Aq; .Ve .PP More usefully, settings can be defined in a configuration file. Environment-specific settings can also be defined in environment-specific files (for instance, you do not want to show error stacktraces in production, and might want extra logging in development). See the cookbook for examples. .SS "Serializers" .IX Subsection "Serializers" When writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer2 can automatically handle that for you, via a serializer. .PP When setting up a serializer, a new behaviour is authorized for any route handler you define: any non-scalar response will be rendered as a serialized string, via the current serializer. .PP Here is an example of a route handler that will return a HashRef .PP .Vb 2 \& use Dancer2; \& set serializer => \*(AqJSON\*(Aq; \& \& get \*(Aq/user/:id/\*(Aq => sub { \& { foo => 42, \& number => 100234, \& list => [qw(one two three)], \& } \& }; .Ve .PP As soon as the content is not a scalar \- and a serializer is set, which is not the case by default \- Dancer2 renders the response via the current serializer. .PP Hence, with the \s-1JSON\s0 serializer set, the route handler above would result in a content like the following: .PP .Vb 1 \& {"number":100234,"foo":42,"list":["one","two","three"]} .Ve .PP The following serializers are available, be aware they dynamically depend on Perl modules you may not have on your system. .IP "\fB\s-1JSON\s0\fR" 4 .IX Item "JSON" requires \s-1JSON\s0 .IP "\fB\s-1YAML\s0\fR" 4 .IX Item "YAML" requires \s-1YAML\s0 .IP "\fB\s-1XML\s0\fR" 4 .IX Item "XML" requires XML::Simple .IP "\fBMutable\fR" 4 .IX Item "Mutable" will try to find the appropriate serializer using the \fBContent-Type\fR and \&\fBAccept-type\fR header of the request. .SS "Logging" .IX Subsection "Logging" It's possible to log messages sent by the application. In the current version, only one method is possible for logging messages but future releases may add additional logging methods, for instance logging to syslog. .PP In order to enable the logging system for your application, you first have to start the logger engine in your config file: .PP .Vb 1 \& logger: \*(Aqfile\*(Aq .Ve .PP Then you can choose which kind of messages you want to actually log: .PP .Vb 5 \& log: \*(Aqcore\*(Aq # will log all messages, including some from Dancer2 itself \& log: \*(Aqdebug\*(Aq # will log debug, info, warning and errors \& log: \*(Aqinfo\*(Aq # will log info, warning and errors \& log: \*(Aqwarning\*(Aq # will log warning and errors \& log: \*(Aqerror\*(Aq # will log only errors .Ve .PP A directory appdir/logs will be created and will host one logfile per environment. The log message contains the time it was written, the \s-1PID\s0 of the current process, the message and the caller information (file and line). .PP To log messages, use the \f(CW\*(C`debug\*(C'\fR, \f(CW\*(C`info\*(C'\fR, \f(CW\*(C`warning\*(C'\fR and \f(CW\*(C`error\*(C'\fR methods, for instance: .PP .Vb 1 \& debug "This is a debug message"; .Ve .SS "Using Templates" .IX Subsection "Using Templates" \fIViews\fR .IX Subsection "Views" .PP It's possible to render the action's content with a template; this is called a view. The `appdir/views' directory is the place where views are located. .PP You can change this location by changing the setting 'views', for instance if your templates are located in the 'templates' directory, do the following: .PP .Vb 1 \& set views => path(dirname(_\|_FILE_\|_), \*(Aqtemplates\*(Aq); .Ve .PP By default, the internal template engine is used (Dancer2::Template::Simple) but you may want to upgrade to Template::Toolkit. If you do so, you have to enable this engine in your settings as explained in Dancer2::Template::TemplateToolkit. If you do so, you'll also have to import the Template module in your application code. .PP In order to render a view, just call the 'template' keyword at the end of the action by giving the view name and the \s-1HASHREF\s0 of tokens to interpolate in the view (note that the request, session and route params are automatically accessible in the view, named request, session and params): .PP .Vb 2 \& use Dancer2; \& use Template; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& template \*(Aqhello\*(Aq => { number => 42 }; \& }; .Ve .PP And the appdir/views/hello.tt view can contain the following code: .PP .Vb 11 \& \& \& \&

Hello [% params.name %]

\&

Your lucky number is [% number %]

\&

You are using [% request.user_agent %]

\& [% IF session.user %] \&

You\*(Aqre logged in as [% session.user %]

\& [% END %] \& \& .Ve .PP By default, views use a \f(CW\*(C`.tt\*(C'\fR extension. This can be overridden by setting the \f(CW\*(C`extension\*(C'\fR attribute in the template engine configuration like so: .PP .Vb 7 \& set engines => { \& template => { \& template_toolkit => { \& extension => \*(Aqfoo\*(Aq, \& }, \& }, \& }; .Ve .PP \fILayouts\fR .IX Subsection "Layouts" .PP A layout is a special view, located in the 'layouts' directory (inside the views directory) which must have a token named `content'. That token marks the place where to render the action view. This lets you define a global layout for your actions. Any tokens that you defined when you called the \&'template' keyword are available in the layouts, as well as the standard session, request, and params tokens. This allows you to insert per-page content into the \s-1HTML\s0 boilerplate, such as page titles, current-page tags for navigation, etc. .PP Here is an example of a layout: views/layouts/main.tt: .PP .Vb 6 \& \& [% page_title %] \& \& \& \&
\& [% content %] \&
\& \& \& .Ve .PP This layout can be used like the following: .PP .Vb 2 \& use Dancer2; \& set layout => \*(Aqmain\*(Aq; \& \& get \*(Aq/\*(Aq => sub { \& template \*(Aqindex\*(Aq => { page_title => "Your website Homepage" }; \& }; .Ve .PP Of course, if a layout is set, it can also be disabled for a specific action, like the following: .PP .Vb 2 \& use Dancer2; \& set layout => \*(Aqmain\*(Aq; \& \& get \*(Aq/nolayout\*(Aq => sub { \& template \*(Aqsome_ajax_view\*(Aq, \& { tokens_var => "42" }, \& { layout => 0 }; \& }; .Ve .SS "Static Files" .IX Subsection "Static Files" \fIStatic Directory\fR .IX Subsection "Static Directory" .PP Static files are served from the ./public directory. You can specify a different location by setting the 'public' option: .PP .Vb 1 \& set public => path(dirname(_\|_FILE_\|_), \*(Aqstatic\*(Aq); .Ve .PP Note that the public directory name is not included in the \s-1URL. A\s0 file \&./public/css/style.css is made available as example.com/css/style.css. .PP \fIStatic File from a Route Handler\fR .IX Subsection "Static File from a Route Handler" .PP It's possible for a route handler to send a static file, as follows: .PP .Vb 3 \& get \*(Aq/download/*\*(Aq => sub { \& my $params = shift; \& my ($file) = @{ $params\->{splat} }; \& \& send_file $file; \& }; .Ve .PP Or even if you want your index page to be a plain old index.html file, just do: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& send_file \*(Aq/index.html\*(Aq \& }; .Ve .SH "EXPORTS" .IX Header "EXPORTS" By default, \f(CW\*(C`use Dancer2\*(C'\fR exports all the \s-1DSL\s0 keywords and sets up the webapp under the name of the current package. The following tags control exports and webapp namespace. .IP "\fB!keyword\fR" 4 .IX Item "!keyword" If you want to prevent Dancer2 from exporting specific keywords; perhaps you plan to implement them yourself in a different way, or they clash with another module you're loading, you can simply exclude them: .Sp .Vb 2 \& use Test::More; \& use Dancer2 qw(!pass); .Ve .Sp The above would import all keywords as normal, with the exception of \f(CW\*(C`pass\*(C'\fR. .IP "\fBappname\fR" 4 .IX Item "appname" A larger application may split its source between several packages to aid maintainability. Dancer2 will create a separate application for each package, each having separate hooks, config and/or engines. You can force Dancer2 to collect the route and hooks into a single application with the \&\f(CW\*(C`appname\*(C'\fR tag; e.g. .Sp .Vb 3 \& package MyApp; \& use Dancer2; \& get \*(Aq/foo\*(Aq => sub {...}; \& \& package MyApp::Private; \& use Dancer2 appname => MyApp; \& get \*(Aq/bar\*(Aq => sub {...}; .Ve .Sp The above would add the \f(CW\*(C`bar\*(C'\fR route to the MyApp application. Dancer2 will not create an application with the name \f(CW\*(C`MyApp::Private\*(C'\fR. .PP When you \f(CW\*(C`use Dancer2\*(C'\fR, you get an \f(CW\*(C`import\*(C'\fR method added into the current package. This \fBwill\fR override previously declared import methods from other sources, such as Exporter. Dancer2 applications support the following tags on import: .IP "\fBwith\fR" 4 .IX Item "with" The \f(CW\*(C`with\*(C'\fR tag allows an app to pass one or more config entries to another app, when it \f(CW\*(C`use\*(C'\fRs it. .Sp .Vb 2 \& package MyApp; \& use Dancer2; \& \& set session => \*(AqYAML\*(Aq; \& use Blog with => { session => engine(\*(Aqsession\*(Aq) }; .Ve .Sp In this example, the session engine is passed to the \f(CW\*(C`Blog\*(C'\fR app. That way, anything done in the session will be shared between both apps. .Sp Anything that is defined in the config entry can be passed that way. If we want to pass the whole config object, it can be done like so: .Sp .Vb 1 \& use SomeApp with => { %{config()} }; .Ve .SH "DSL KEYWORDS" .IX Header "DSL KEYWORDS" Dancer2 provides you with a \s-1DSL \s0(Domain-Specific Language) which makes implementing your web application trivial. .PP For example, take the following example: .PP .Vb 1 \& use Dancer2; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& my $name = params\->{name}; \& }; \& dance; .Ve .PP \&\f(CW\*(C`get\*(C'\fR and \f(CW\*(C`params\*(C'\fR are keywords provided by Dancer2. .PP This document lists all keywords provided by Dancer2. It does not cover additional keywords which may be provided by loaded plugins; see the documentation for plugins you use to see which additional keywords they make available to you. .SS "any" .IX Subsection "any" Defines a route for multiple \s-1HTTP\s0 methods at once: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP Or even, a route handler that would match any \s-1HTTP\s0 methods: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .SS "cookies" .IX Subsection "cookies" Accesses cookies values, it returns a HashRef of Dancer2::Core::Cookie objects: .PP .Vb 4 \& get \*(Aq/some_action\*(Aq => sub { \& my $cookie = cookies\->{name}; \& return $cookie\->value; \& }; .Ve .PP In the case you have stored something else than a Scalar in your cookie: .PP .Vb 5 \& get \*(Aq/some_action\*(Aq => sub { \& my $cookie = cookies\->{oauth}; \& my %values = $cookie\->value; \& return ($values{token}, $values{token_secret}); \& }; .Ve .SS "cookie" .IX Subsection "cookie" Accesses a cookie value (or sets it). Note that this method will eventually be preferred over \f(CW\*(C`set_cookie\*(C'\fR. .PP .Vb 3 \& cookie lang => "fr\-FR"; # set a cookie and return its value \& cookie lang => "fr\-FR", expires => "2 hours"; # extra cookie info \& cookie "lang" # return a cookie value .Ve .PP If your cookie value is a key/value \s-1URI\s0 string, like .PP .Vb 1 \& token=ABC&user=foo .Ve .PP \&\f(CW\*(C`cookie\*(C'\fR will only return the first part (\f(CW\*(C`token=ABC\*(C'\fR) if called in scalar context. Use list context to fetch them all: .PP .Vb 1 \& my @values = cookie "name"; .Ve .SS "config" .IX Subsection "config" Accesses the configuration of the application: .PP .Vb 3 \& get \*(Aq/appname\*(Aq => sub { \& return "This is " . config\->{appname}; \& }; .Ve .SS "content" .IX Subsection "content" Sets the content for the response. .PP .Vb 2 \& get \*(Aq/\*(Aq => sub { \& content \*(AqHello, world!\*(Aq; \& \& # the return value of the route is ignored \& return \*(AqIgnored String\*(Aq; \& }; .Ve .PP Once you set the content using the keyword, your return value (which is usually the content) is ignored. .PP \&\fB\s-1WARNING\s0\fR : If you are using the \f(CW\*(C`pass\*(C'\fR keyword, the last route will be in charge of setting the content. .SS "content_type" .IX Subsection "content_type" Sets the \fBcontent-type\fR rendered, for the current route handler: .PP .Vb 2 \& get \*(Aq/cat/:txtfile\*(Aq => sub { \& content_type \*(Aqtext/plain\*(Aq; \& \& # here we can dump the contents of param(\*(Aqtxtfile\*(Aq) \& }; .Ve .PP You can use abbreviations for content types. For instance: .PP .Vb 2 \& get \*(Aq/svg/:id\*(Aq => sub { \& content_type \*(Aqsvg\*(Aq; \& \& # here we can dump the image with id param(\*(Aqid\*(Aq) \& }; .Ve .PP Note that if you want to change the default content-type for every route, you have to change the \f(CW\*(C`content_type\*(C'\fR setting instead. .SS "dance" .IX Subsection "dance" Alias for the \f(CW\*(C`start\*(C'\fR keyword. .SS "dancer_version" .IX Subsection "dancer_version" Returns the version of Dancer. If you need the major version, do something like: .PP .Vb 1 \& int(dancer_version); .Ve .SS "debug" .IX Subsection "debug" Logs a message of debug level: .PP .Vb 1 \& debug "This is a debug message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "dirname" .IX Subsection "dirname" Returns the dirname of the path given: .PP .Vb 1 \& my $dir = dirname($some_path); .Ve .SS "engine" .IX Subsection "engine" Given a namespace, returns the current engine object .PP .Vb 3 \& my $template_engine = engine \*(Aqtemplate\*(Aq; \& my $html = $template_engine\->apply_renderer(...); \& $template_engine\->apply_layout($html); .Ve .SS "error" .IX Subsection "error" Logs a message of error level: .PP .Vb 1 \& error "This is an error message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "false" .IX Subsection "false" Constant that returns a false value (0). .SS "forward" .IX Subsection "forward" Runs an \*(L"internal redirect\*(R" of the current request to another request. More formally; when the \f(CW\*(C`forward\*(C'\fR is executed, the current dispatch of the request is aborted, the request is modified (altering query params or request method), and the modified request is dispatched again. Any remaining code (route and hooks) from the current dispatch will never be run and the modified request's dispatch will execute hooks for the new request normally. .PP It effectively lets you chain routes together in a clean manner. .PP .Vb 1 \& get \*(Aq/demo/articles/:article_id\*(Aq => sub { \& \& # you\*(Aqll have to implement this next sub yourself :) \& change_the_main_database_to_demo(); \& \& forward "/articles/" . params\->{article_id}; \& }; .Ve .PP In the above example, the users that reach \fI/demo/articles/30\fR will actually reach \fI/articles/30\fR but we've changed the database to demo before. .PP This is pretty cool because it lets us retain our paths and offer a demo database by merely going to \fI/demo/...\fR. .PP You'll notice that in the example we didn't indicate whether it was \fB\s-1GET\s0\fR or \fB\s-1POST\s0\fR. That is because \f(CW\*(C`forward\*(C'\fR chains the same type of route the user reached. If it was a \fB\s-1GET\s0\fR, it will remain a \fB\s-1GET\s0\fR (but if you do need to change the method, you can do so; read on below for details.) .PP \&\fB\s-1WARNING\s0\fR : Any code after a \f(CW\*(C`forward\*(C'\fR is ignored, until the end of the route. It's not necessary to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`forward\*(C'\fR anymore. .PP .Vb 6 \& get \*(Aq/foo/:article_id\*(Aq => sub { \& if ($condition) { \& forward "/articles/" . params\->{article_id}; \& # The following code WILL NOT BE executed \& do_stuff(); \& } \& \& more_stuff(); \& }; .Ve .PP Note that \f(CW\*(C`forward\*(C'\fR doesn't parse \s-1GET\s0 arguments. So, you can't use something like: .PP .Vb 1 \& forward \*(Aq/home?authorized=1\*(Aq; .Ve .PP But \f(CW\*(C`forward\*(C'\fR supports an optional HashRef with parameters to be added to the actual parameters: .PP .Vb 1 \& forward \*(Aq/home\*(Aq, { authorized => 1 }; .Ve .PP Finally, you can add some more options to the \f(CW\*(C`forward\*(C'\fR method, in a third argument, also as a HashRef. That option is currently only used to change the method of your request. Use with caution. .PP .Vb 1 \& forward \*(Aq/home\*(Aq, { auth => 1 }, { method => \*(AqPOST\*(Aq }; .Ve .SS "from_dumper ($structure)" .IX Subsection "from_dumper ($structure)" Deserializes a Data::Dumper structure. .SS "from_json ($structure, \e%options)" .IX Subsection "from_json ($structure, %options)" Deserializes a \s-1JSON\s0 structure. Can receive optional arguments. Those arguments are valid \s-1JSON\s0 arguments to change the behaviour of the default \&\f(CW\*(C`JSON::from_json\*(C'\fR function. .SS "from_yaml ($structure)" .IX Subsection "from_yaml ($structure)" Deserializes a \s-1YAML\s0 structure. .SS "get" .IX Subsection "get" Defines a route for \s-1HTTP \s0\fB\s-1GET\s0\fR requests to the given path: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& return "Hello world"; \& } .Ve .PP Note that a route to match \fB\s-1HEAD\s0\fR requests is automatically created as well. .SS "halt" .IX Subsection "halt" Sets a response object with the content given. .PP When used as a return value from a filter, this breaks the execution flow and renders the response immediately: .PP .Vb 7 \& hook before => sub { \& if ($some_condition) { \& halt("Unauthorized"); \& # This code is not executed : \& do_stuff(); \& } \& }; \& \& get \*(Aq/\*(Aq => sub { \& "hello there"; \& }; .Ve .PP \&\fB\s-1WARNING\s0\fR : Issuing a halt immediately exits the current route, and perform the halt. Thus, any code after a halt is ignored, until the end of the route. So it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with halt. .SS "headers" .IX Subsection "headers" Adds custom headers to responses: .PP .Vb 3 \& get \*(Aq/send/headers\*(Aq, sub { \& headers \*(AqX\-Foo\*(Aq => \*(Aqbar\*(Aq, X\-Bar => \*(Aqfoo\*(Aq; \& } .Ve .SS "header" .IX Subsection "header" adds a custom header to response: .PP .Vb 3 \& get \*(Aq/send/header\*(Aq, sub { \& header \*(Aqx\-my\-header\*(Aq => \*(Aqshazam!\*(Aq; \& } .Ve .PP Note that it will overwrite the old value of the header, if any. To avoid that, see \*(L"push_header\*(R". .SS "push_header" .IX Subsection "push_header" Do the same as \f(CW\*(C`header\*(C'\fR, but allow for multiple headers with the same name. .PP .Vb 5 \& get \*(Aq/send/header\*(Aq, sub { \& push_header \*(Aqx\-my\-header\*(Aq => \*(Aq1\*(Aq; \& push_header \*(Aqx\-my\-header\*(Aq => \*(Aq2\*(Aq; \& will result in two headers "x\-my\-header" in the response \& } .Ve .SS "hook" .IX Subsection "hook" Adds a hook at some position. For example : .PP .Vb 4 \& hook before_serializer => sub { \& my $content = shift; \& ... \& }; .Ve .PP There can be multiple hooks assigned to a given position, and each will be executed in order. .SS "info" .IX Subsection "info" Logs a message of info level: .PP .Vb 1 \& info "This is a info message"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SS "load" .IX Subsection "load" Loads one or more perl scripts in the current application's namespace. Syntactic sugar around Perl's \f(CW\*(C`require\*(C'\fR: .PP .Vb 1 \& load \*(AqUserActions.pl\*(Aq, \*(AqAdminActions.pl\*(Aq; .Ve .SS "mime" .IX Subsection "mime" Shortcut to access the instance object of Dancer2::Core::MIME. You should read the Dancer2::Core::MIME documentation for full details, but the most commonly-used methods are summarized below: .PP .Vb 2 \& # set a new mime type \& mime\->add_type( foo => \*(Aqtext/foo\*(Aq ); \& \& # set a mime type alias \& mime\->add_alias( f => \*(Aqfoo\*(Aq ); \& \& # get mime type for an alias \& my $m = mime\->for_name( \*(Aqf\*(Aq ); \& \& # get mime type for a file (based on extension) \& my $m = mime\->for_file( "foo.bar" ); \& \& # get current defined default mime type \& my $d = mime\->default; \& \& # set the default mime type using config.yml \& # or using the set keyword \& set default_mime_type => \*(Aqtext/plain\*(Aq; .Ve .SS "params" .IX Subsection "params" \&\fIThis method should be called from a route handler\fR. It's an alias for the Dancer2::Core::Request params accessor. It returns a hash (in list context) or a hash reference (in scalar context) to all defined parameters. Check \f(CW\*(C`param\*(C'\fR below to access quickly to a single parameter value. .SS "param" .IX Subsection "param" \&\fIThis method should be called from a route handler\fR. This method is an accessor to the parameters hash table. .PP .Vb 5 \& post \*(Aq/login\*(Aq => sub { \& my $username = param "user"; \& my $password = param "pass"; \& # ... \& } .Ve .SS "pass" .IX Subsection "pass" \&\fIThis method should be called from a route handler\fR. Tells Dancer to pass the processing of the request to the next matching route. .PP \&\fB\s-1WARNING\s0\fR : Issuing a pass immediately exits the current route, and perform the pass. Thus, any code after a pass is ignored, until the end of the route. So it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with pass. .PP .Vb 8 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # we want to let the next matching route handler process this one \& pass(...); \& # This code will be ignored \& do_stuff(); \& } \& }; .Ve .PP \&\fB\s-1WARNING\s0\fR : You cannot set the content before passing and have it remain, even if you use the \f(CW\*(C`content\*(C'\fR keyword or set it directly in the response object. .SS "patch" .IX Subsection "patch" Defines a route for \s-1HTTP \s0\fB\s-1PATCH\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& patch \*(Aq/resource\*(Aq => sub { ... }; .Ve .PP (\f(CW\*(C`PATCH\*(C'\fR is a relatively new and not-yet-common \s-1HTTP\s0 verb, which is intended to work as a \*(L"partial-PUT\*(R", transferring just the changes; please see for further details.) .PP Please be aware that, if you run your app in standalone mode, \f(CW\*(C`PATCH\*(C'\fR requests will not reach your app unless you have a new version of HTTP::Server::Simple which accepts \f(CW\*(C`PATCH\*(C'\fR as a valid verb. The current version at time of writing, \f(CW0.44\fR, does not. A pull request has been submitted to add this support, which you can find at: .PP .SS "path" .IX Subsection "path" Concatenates multiple paths together, without worrying about the underlying operating system: .PP .Vb 1 \& my $path = path(dirname($0), \*(Aqlib\*(Aq, \*(AqFile.pm\*(Aq); .Ve .PP It also normalizes (cleans) the path aesthetically. It does not verify the path exists. .SS "post" .IX Subsection "post" Defines a route for \s-1HTTP \s0\fB\s-1POST\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 3 \& post \*(Aq/\*(Aq => sub { \& return "Hello world"; \& } .Ve .SS "prefix" .IX Subsection "prefix" Defines a prefix for each route handler, like this: .PP .Vb 1 \& prefix \*(Aq/home\*(Aq; .Ve .PP From here, any route handler is defined to /home/*: .PP .Vb 1 \& get \*(Aq/page1\*(Aq => sub {}; # will match \*(Aq/home/page1\*(Aq .Ve .PP You can unset the prefix value: .PP .Vb 2 \& prefix undef; \& get \*(Aq/page1\*(Aq => sub {}; # will match /page1 .Ve .PP For a safer alternative you can use lexical prefix like this: .PP .Vb 2 \& prefix \*(Aq/home\*(Aq => sub { \& ## Prefix is set to \*(Aq/home\*(Aq here \& \& get ...; \& get ...; \& }; \& ## prefix reset to the previous version here .Ve .PP This makes it possible to nest prefixes: .PP .Vb 2 \& prefix \*(Aq/home\*(Aq => sub { \& ## some routes \& \& prefix \*(Aq/private\*(Aq => sub { \& ## here we are under /home/private... \& \& ## some more routes \& }; \& ## back to /home \& }; \& ## back to the root .Ve .PP \&\fBNotice:\fR once you have a prefix set, do not add a caret to the regex: .PP .Vb 3 \& prefix \*(Aq/foo\*(Aq; \& get qr{^/bar} => sub { ... } # BAD BAD BAD \& get qr{/bar} => sub { ... } # Good! .Ve .SS "del" .IX Subsection "del" Defines a route for \s-1HTTP \s0\fB\s-1DELETE\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& del \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "options" .IX Subsection "options" Defines a route for \s-1HTTP \s0\fB\s-1OPTIONS\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& options \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "put" .IX Subsection "put" Defines a route for \s-1HTTP \s0\fB\s-1PUT\s0\fR requests to the given \s-1URL:\s0 .PP .Vb 1 \& put \*(Aq/resource\*(Aq => sub { ... }; .Ve .SS "redirect" .IX Subsection "redirect" Generates a \s-1HTTP\s0 redirect (302). You can either redirect to a complete different site or within the application: .PP .Vb 4 \& get \*(Aq/twitter\*(Aq, sub { \& redirect \*(Aqhttp://twitter.com/me\*(Aq; \& # Any code after the redirect will not be executed. \& }; .Ve .PP \&\fB\s-1WARNING\s0\fR : Issuing a \f(CW\*(C`redirect\*(C'\fR immediately exits the current route. Thus, any code after a \f(CW\*(C`redirect\*(C'\fR is ignored, until the end of the route. So it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with \f(CW\*(C`redirect\*(C'\fR. .PP You can also force Dancer to return a specific 300\-ish \s-1HTTP\s0 response code: .PP .Vb 3 \& get \*(Aq/old/:resource\*(Aq, sub { \& redirect \*(Aq/new/\*(Aq.params\->{resource}, 301; \& }; .Ve .SS "request" .IX Subsection "request" Returns a Dancer2::Core::Request object representing the current request. .PP See the Dancer2::Core::Request documentation for the methods you can call, for example: .PP .Vb 3 \& request\->referer; # value of the HTTP referer header \& request\->remote_address; # user\*(Aqs IP address \& request\->user_agent; # User\-Agent header value .Ve .SS "send_error" .IX Subsection "send_error" Returns a \s-1HTTP\s0 error. By default the \s-1HTTP\s0 code returned is 500: .PP .Vb 7 \& get \*(Aq/photo/:id\*(Aq => sub { \& if (...) { \& send_error("Not allowed", 403); \& } else { \& # return content \& } \& } .Ve .PP \&\fB\s-1WARNING\s0\fR : Issuing a send_error immediately exits the current route, and perform the send_error. Thus, any code after a send_error is ignored, until the end of the route. So it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with send_error. .PP .Vb 8 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # we want to let the next matching route handler process this one \& send_error(..); \& # This code will be ignored \& do_stuff(); \& } \& }; .Ve .SS "send_file" .IX Subsection "send_file" Lets the current route handler send a file to the client. Note that the path of the file must be relative to the \fBpublic\fR directory unless you use the \&\f(CW\*(C`system_path\*(C'\fR option (see below). .PP .Vb 3 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file(params\->{file}); \& } .Ve .PP \&\fB\s-1WARNING\s0\fR : Issuing a send_file immediately exits the current route, and perform the send_file. Thus, any code after a send_file is ignored, until the end of the route. So it's not necessary anymore to use \f(CW\*(C`return\*(C'\fR with send_file. .PP .Vb 8 \& get \*(Aq/some/route\*(Aq => sub { \& if (...) { \& # we want to let the next matching route handler process this one \& send_file(...); \& # This code will be ignored \& do_stuff(); \& } \& }; .Ve .PP Send file supports streaming possibility using \s-1PSGI\s0 streaming. The server should support it but normal streaming is supported on most, if not all. .PP .Vb 3 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file( params\->{file}, streaming => 1 ); \& } .Ve .PP You can control what happens using callbacks. .PP First, \f(CW\*(C`around_content\*(C'\fR allows you to get the writer object and the chunk of content read, and then decide what to do with each chunk: .PP .Vb 12 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file( \& params\->{file}, \& streaming => 1, \& callbacks => { \& around_content => sub { \& my ( $writer, $chunk ) = @_; \& $writer\->write("* $chunk"); \& }, \& }, \& ); \& } .Ve .PP You can use \f(CW\*(C`around\*(C'\fR to get all the content (whether a filehandle if it's a regular file or a full string if it's a scalar ref) and decide what to do with it: .PP .Vb 7 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file( \& params\->{file}, \& streaming => 1, \& callbacks => { \& around => sub { \& my ( $writer, $content ) = @_; \& \& # we know it\*(Aqs a text file, so we\*(Aqll just stream \& # line by line \& while ( my $line = <$content> ) { \& $writer\->write($line); \& } \& }, \& }, \& ); \& } .Ve .PP Or you could use \f(CW\*(C`override\*(C'\fR to control the entire streaming callback request: .PP .Vb 7 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file( \& params\->{file}, \& streaming => 1, \& callbacks => { \& override => sub { \& my ( $respond, $response ) = @_; \& \& my $writer = $respond\->( [ $newstatus, $newheaders ] ); \& $writer\->write("some line"); \& }, \& }, \& ); \& } .Ve .PP You can also set the number of bytes that will be read at a time (default being 42K bytes) using \f(CW\*(C`bytes\*(C'\fR: .PP .Vb 7 \& get \*(Aq/download/:file\*(Aq => sub { \& return send_file( \& params\->{file}, \& streaming => 1, \& bytes => 524288, # 512K \& ); \& }; .Ve .PP The content-type will be set depending on the current \s-1MIME\s0 types definition (see \f(CW\*(C`mime\*(C'\fR if you want to define your own). .PP If your filename does not have an extension, or you need to force a specific mime type, you can pass it to \f(CW\*(C`send_file\*(C'\fR as follows: .PP .Vb 1 \& return send_file(params\->{file}, content_type => \*(Aqimage/png\*(Aq); .Ve .PP Also, you can use your aliases or file extension names on \f(CW\*(C`content_type\*(C'\fR, like this: .PP .Vb 1 \& return send_file(params\->{file}, content_type => \*(Aqpng\*(Aq); .Ve .PP For files outside your \fBpublic\fR folder, you can use the \f(CW\*(C`system_path\*(C'\fR switch. Just bear in mind that its use needs caution as it can be dangerous. .PP .Vb 1 \& return send_file(\*(Aq/etc/passwd\*(Aq, system_path => 1); .Ve .PP If you have your data in a scalar variable, \f(CW\*(C`send_file\*(C'\fR can be useful as well. Pass a reference to that scalar, and \f(CW\*(C`send_file\*(C'\fR will behave as if there was a file with that contents: .PP .Vb 1 \& return send_file( \e$data, content_type => \*(Aqimage/png\*(Aq ); .Ve .PP Note that Dancer is unable to guess the content type from the data contents. Therefore you might need to set the \f(CW\*(C`content_type\*(C'\fR properly. For this kind of usage an attribute named \f(CW\*(C`filename\*(C'\fR can be useful. It is used as the Content-Disposition header, to hint the browser about the filename it should use. .PP .Vb 2 \& return send_file( \e$data, content_type => \*(Aqimage/png\*(Aq \& filename => \*(Aqonion.png\*(Aq ); .Ve .PP Note that you should always use \f(CW\*(C`return send_file ...\*(C'\fR to stop execution of your route handler at that point. .SS "set" .IX Subsection "set" Defines a setting: .PP .Vb 1 \& set something => \*(Aqvalue\*(Aq; .Ve .PP You can set more than one value at once: .PP .Vb 1 \& set something => \*(Aqvalue\*(Aq, otherthing => \*(Aqothervalue\*(Aq; .Ve .SS "setting" .IX Subsection "setting" Returns the value of a given setting: .PP .Vb 1 \& setting(\*(Aqsomething\*(Aq); # \*(Aqvalue\*(Aq .Ve .SS "session" .IX Subsection "session" Provides access to all data stored in the user's session (if any). .PP It can also be used as a setter to store data in the session: .PP .Vb 6 \& # getter example \& get \*(Aq/user\*(Aq => sub { \& if (session(\*(Aquser\*(Aq)) { \& return "Hello, ".session(\*(Aquser\*(Aq)\->name; \& } \& }; \& \& # setter example \& post \*(Aq/user/login\*(Aq => sub { \& ... \& if ($logged_in) { \& session user => $user; \& } \& ... \& }; .Ve .PP You may also need to clear a session: .PP .Vb 6 \& # destroy session \& get \*(Aq/logout\*(Aq => sub { \& ... \& app\->destroy_session; \& ... \& }; .Ve .PP If you need to fetch the session \s-1ID\s0 being used for any reason: .PP .Vb 1 \& my $id = session\->id; .Ve .SS "splat" .IX Subsection "splat" Returns the list of captures made from a route handler with a route pattern which includes wildcards: .PP .Vb 4 \& get \*(Aq/file/*.*\*(Aq => sub { \& my ($file, $extension) = splat; \& ... \& }; .Ve .PP There is also the extensive splat (A.K.A. \*(L"megasplat\*(R"), which allows extensive greedier matching, available using two asterisks. The additional path is broken down and returned as an ArrayRef: .PP .Vb 4 \& get \*(Aq/entry/*/tags/**\*(Aq => sub { \& my ( $entry_id, $tags ) = splat; \& my @tags = @{$tags}; \& }; .Ve .PP This helps with chained actions: .PP .Vb 5 \& get \*(Aq/team/*/**\*(Aq => sub { \& my ($team) = splat; \& var team => $team; \& pass; \& }; \& \& prefix \*(Aq/team/*\*(Aq; \& \& get \*(Aq/player/*\*(Aq => sub { \& my ($player) = splat; \& \& # etc... \& }; \& \& get \*(Aq/score\*(Aq => sub { \& return score_for( vars\->{\*(Aqteam\*(Aq} ); \& }; .Ve .SS "start" .IX Subsection "start" Starts the application or the standalone server (depending on the deployment choices). .PP This keyword should be called at the very end of the script, once all routes are defined. At this point, Dancer takes over control. .SS "to_app" .IX Subsection "to_app" Returns the \s-1PSGI\s0 coderef for the current (and only the current) application. .PP You can call it as a method on the class or as a \s-1DSL:\s0 .PP .Vb 1 \& my $app = MyApp\->to_app; \& \& # or \& \& my $app = to_app; .Ve .SS "psgi_app" .IX Subsection "psgi_app" Provides the same functionality as \f(CW\*(C`to_app\*(C'\fR but uses the deprecated Dispatcher engine. You should use \f(CW\*(C`to_app\*(C'\fR. .SS "status" .IX Subsection "status" Changes the status code provided by an action. By default, an action will produce an \f(CW\*(C`HTTP 200 OK\*(C'\fR status code, meaning everything is \s-1OK:\s0 .PP .Vb 7 \& get \*(Aq/download/:file\*(Aq => { \& if (! \-f params\->{file}) { \& status \*(Aqnot_found\*(Aq; \& return "File does not exist, unable to download"; \& } \& # serving the file... \& }; .Ve .PP In that example, Dancer will notice that the status has changed, and will render the response accordingly. .PP The status keyword receives either a numeric status code or its name in lower case, with underscores as a separator for blanks \- see the list in \&\*(L"\s-1HTTP CODES\*(R"\s0 in Dancer2::Core::HTTP. .SS "template" .IX Subsection "template" Returns the response of processing the given template with the given parameters (and optional settings), wrapping it in the default or specified layout too, if layouts are in use. .PP An example of a route handler which returns the result of using template to build a response with the current template engine: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& ... \& return template \*(Aqsome_view\*(Aq, { token => \*(Aqvalue\*(Aq}; \& }; .Ve .PP Note that \f(CW\*(C`template\*(C'\fR simply returns the content, so when you use it in a route handler, if execution of the route handler should stop at that point, make sure you use 'return' to ensure your route handler returns the content. .PP Since template just returns the result of rendering the template, you can also use it to perform other templating tasks, e.g. generating emails: .PP .Vb 8 \& post \*(Aq/some/route\*(Aq => sub { \& if (...) { \& email { \& to => \*(Aqsomeone@example.com\*(Aq, \& from => \*(Aqfoo@example.com\*(Aq, \& subject => \*(AqHello there\*(Aq, \& msg => template(\*(Aqemails/foo\*(Aq, { name => params\->{name} }), \& }; \& \& return template \*(Aqmessage_sent\*(Aq; \& } else { \& return template \*(Aqerror\*(Aq; \& } \& }; .Ve .PP Compatibility notice: \f(CW\*(C`template\*(C'\fR was changed in version 1.3090 to immediately interrupt execution of a route handler and return the content, as it's typically used at the end of a route handler to return content. However, this caused issues for some people who were using \f(CW\*(C`template\*(C'\fR to generate emails etc, rather than accessing the template engine directly, so this change has been reverted in 1.3091. .PP The first parameter should be a template available in the views directory, the second one (optional) is a HashRef of tokens to interpolate, and the third (again optional) is a HashRef of options. .PP For example, to disable the layout for a specific request: .PP .Vb 3 \& get \*(Aq/\*(Aq => sub { \& template \*(Aqindex\*(Aq, {}, { layout => undef }; \& }; .Ve .PP Or to request a specific layout, of course: .PP .Vb 3 \& get \*(Aq/user\*(Aq => sub { \& template \*(Aquser\*(Aq, {}, { layout => \*(Aquser\*(Aq }; \& }; .Ve .PP Some tokens are automatically added to your template (\f(CW\*(C`perl_version\*(C'\fR, \&\f(CW\*(C`dancer_version\*(C'\fR, \f(CW\*(C`settings\*(C'\fR, \f(CW\*(C`request\*(C'\fR, \f(CW\*(C`params\*(C'\fR, \f(CW\*(C`vars\*(C'\fR and, if you have sessions enabled, \f(CW\*(C`session\*(C'\fR). Check Dancer2::Core::Role::Template for further details. .SS "to_dumper ($structure)" .IX Subsection "to_dumper ($structure)" Serializes a structure with Data::Dumper. .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "to_json ($structure, \e%options)" .IX Subsection "to_json ($structure, %options)" Serializes a structure to \s-1JSON.\s0 Can receive optional arguments. Thoses arguments are valid \s-1JSON\s0 arguments to change the behaviour of the default \&\f(CW\*(C`JSON::to_json\*(C'\fR function. .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "to_yaml ($structure)" .IX Subsection "to_yaml ($structure)" Serializes a structure to \s-1YAML.\s0 .PP Calling this function will \fBnot\fR trigger the serialization's hooks. .SS "true" .IX Subsection "true" Constant that returns a true value (1). .SS "upload" .IX Subsection "upload" Provides access to file uploads. Any uploaded file is accessible as a Dancer2::Core::Request::Upload object. You can access all parsed uploads via: .PP .Vb 4 \& post \*(Aq/some/route\*(Aq => sub { \& my $file = upload(\*(Aqfile_input_foo\*(Aq); \& # file is a Dancer2::Core::Request::Upload object \& }; .Ve .PP If you named multiple input of type \*(L"file\*(R" with the same name, the upload keyword will return an Array of Dancer2::Core::Request::Upload objects: .PP .Vb 4 \& post \*(Aq/some/route\*(Aq => sub { \& my ($file1, $file2) = upload(\*(Aqfiles_input\*(Aq); \& # $file1 and $file2 are Dancer2::Core::Request::Upload objects \& }; .Ve .PP You can also access the raw HashRef of parsed uploads via the current request object: .PP .Vb 5 \& post \*(Aq/some/route\*(Aq => sub { \& my $all_uploads = request\->uploads; \& # $all_uploads\->{\*(Aqfile_input_foo\*(Aq} is a Dancer2::Core::Request::Upload object \& # $all_uploads\->{\*(Aqfiles_input\*(Aq} is an ArrayRef of Dancer2::Core::Request::Upload objects \& }; .Ve .PP Note that you can also access the filename of the upload received via the params keyword: .PP .Vb 3 \& post \*(Aq/some/route\*(Aq => sub { \& # params\->{\*(Aqfiles_input\*(Aq} is the filename of the file uploaded \& }; .Ve .PP See Dancer2::Core::Request::Upload for details about the interface provided. .SS "uri_for" .IX Subsection "uri_for" Returns a fully-qualified \s-1URI\s0 for the given path: .PP .Vb 4 \& get \*(Aq/\*(Aq => sub { \& redirect uri_for(\*(Aq/path\*(Aq); \& # can be something like: http://localhost:3000/path \& }; .Ve .SS "captures" .IX Subsection "captures" Returns a reference to a copy of \f(CW\*(C`%+\*(C'\fR, if there are named captures in the route Regexp. .PP Named captures are a feature of Perl 5.10, and are not supported in earlier versions: .PP .Vb 10 \& get qr{ \& / (? user | ticket | comment ) \& / (? delete | find ) \& / (? \ed+ ) \& /?$ \& }x \& , sub { \& my $value_for = captures; \& "i don\*(Aqt want to $$value_for{action} the $$value_for{object} $$value_for{id} !" \& }; .Ve .SS "var" .IX Subsection "var" Provides an accessor for variables shared between filters and route handlers. Given a key/value pair, it sets a variable: .PP .Vb 3 \& hook before => sub { \& var foo => 42; \& }; .Ve .PP Later, route handlers and other filters will be able to read that variable: .PP .Vb 4 \& get \*(Aq/path\*(Aq => sub { \& my $foo = var \*(Aqfoo\*(Aq; \& ... \& }; .Ve .SS "vars" .IX Subsection "vars" Returns the HashRef of all shared variables set during the filter/route chain with the \f(CW\*(C`var\*(C'\fR keyword: .PP .Vb 5 \& get \*(Aq/path\*(Aq => sub { \& if (vars\->{foo} eq 42) { \& ... \& } \& }; .Ve .SS "warning" .IX Subsection "warning" Logs a warning message through the current logger engine: .PP .Vb 1 \& warning "This is a warning"; .Ve .PP See Dancer2::Core::Role::Logger for details on how to configure where log messages go. .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2014 by Alexis Sukrieh. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.