.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" 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 >0, 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 .\" ======================================================================== .\" .IX Title "Dancer::Introduction 3pm" .TH Dancer::Introduction 3pm "2023-02-10" "perl v5.36.0" "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" Dancer::Introduction \- A gentle introduction to Dancer .SH "VERSION" .IX Header "VERSION" version 1.3521 .SH "DESCRIPTION" .IX Header "DESCRIPTION" Dancer is a free and open source micro web application framework written in Perl. .SH "INSTALL" .IX Header "INSTALL" Installation of Dancer is simple: .PP .Vb 1 \& perl \-MCPAN \-e \*(Aqinstall Dancer\*(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 \- Dancer .Ve .PP (If you don't have root access, omit the 'sudo', and cpanminus will install Dancer and prereqs into \f(CW\*(C`~/perl5\*(C'\fR.) .SH "SETUP" .IX Header "SETUP" Create a web application using the dancer script: .PP .Vb 1 \& dancer \-a MyApp .Ve .PP Run the web application: .PP .Vb 2 \& cd MyApp \& bin/app.pl .Ve .PP You can read the output of \f(CW\*(C`bin/app.pl \-\-help\*(C'\fR to change any settings such as the port number. .PP View the web application at: .PP .Vb 1 \& http://localhost:3000 .Ve .SH "USAGE" .IX Header "USAGE" When Dancer 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 Dancer. .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 METHODS\s0" .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" 8 .IX Item "GET" The \s-1GET\s0 method retrieves information (when defining a route handler for the \s-1GET\s0 method, Dancer 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). To define a \s-1GET\s0 action, use the \fBget\fR keyword. .IP "\fB\s-1POST\s0\fR" 8 .IX Item "POST" The \s-1POST\s0 method is used to create a resource on the server. To define a \s-1POST\s0 action, use the \fBpost\fR keyword. .IP "\fB\s-1PUT\s0\fR" 8 .IX Item "PUT" The \s-1PUT\s0 method is used to update an existing resource. To define a \s-1PUT\s0 action, use the \fBput\fR keyword. .IP "\fB\s-1DELETE\s0\fR" 8 .IX Item "DELETE" The \s-1DELETE\s0 method requests that the origin server delete the resource identified by the Request-URI. To define a \s-1DELETE\s0 action, use the \fBdel\fR 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 "\s-1ROUTE HANDLERS\s0" .IX Subsection "ROUTE HANDLERS" The route action is the code reference declared. It can access parameters through the `params' 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 Dancer::Request documentation. .SS "\s-1NAMED MATCHING\s0" .IX Subsection "NAMED MATCHING" 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 { \& "Hello there " . (param(\*(Aqname\*(Aq) || "whoever you are!"); \& }; .Ve .SS "\s-1WILDCARDS MATCHING\s0" .IX Subsection "WILDCARDS MATCHING" A route can contain a wildcard (represented by a '*'). Each wildcard match will be returned in an arrayref, accessible via the `splat' keyword. .PP .Vb 4 \& get \*(Aq/download/*.*\*(Aq => sub { \& my ($file, $ext) = splat; \& # do something with $file.$ext here \& }; .Ve .SS "\s-1REGULAR EXPRESSION MATCHING\s0" .IX Subsection "REGULAR EXPRESSION MATCHING" A route can be defined with a Perl regular expression. .PP In order to tell Dancer 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 .SS "\s-1CONDITIONAL MATCHING\s0" .IX Subsection "CONDITIONAL MATCHING" 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 "\s-1PREFIX\s0" .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 \*(Aq/page1\*(Aq .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 \*(Aq/page1\*(Aq .Ve .SH "ACTION SKIPPING" .IX Header "ACTION SKIPPING" An action can choose not to serve the current request and ask Dancer 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 "\s-1DEFAULT ERROR PAGES\s0" .IX Subsection "DEFAULT ERROR PAGES" When an error is rendered (the action responded with a status code different than 200), Dancer 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 "\s-1EXECUTION ERRORS\s0" .IX Subsection "EXECUTION ERRORS" When an error occurs during the route execution, Dancer 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" .SS "Before hooks" .IX Subsection "Before hooks" Before hooks are evaluated before each request within the context of the request and can modify the request and response. It's possible to define variables which will be accessible in the action blocks with the keyword 'var'. .PP .Vb 4 \& hook \*(Aqbefore\*(Aq => sub { \& var note => \*(AqHi there\*(Aq; \& request\->path_info(\*(Aq/foo/oversee\*(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 7 \& hook \*(Aqbefore\*(Aq => sub { \& if (!session(\*(Aquser\*(Aq) && request\->path_info !~ m{^/login}) { \& # Pass the original path requested along to the handler: \& var requested_path => request\->path_info; \& request\->path_info(\*(Aq/login\*(Aq); \& } \& }; .Ve .PP The request keyword returns the current Dancer::Request object representing the incoming request. See the documentation of the Dancer::Request module for details. .SS "After hooks" .IX Subsection "After hooks" \&\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 The hook is given the response object as its first argument: .PP .Vb 4 \& hook \*(Aqafter\*(Aq => sub { \& my $response = shift; \& $response\->{content} = \*(Aqafter hook got here!\*(Aq; \& }; .Ve .SS "Before template hook" .IX Subsection "Before template hook" \&\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 \*(Aqbefore_template_render\*(Aq => 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 hook. 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. .SH "CONFIGURATION AND ENVIRONMENTS" .IX Header "CONFIGURATION AND ENVIRONMENTS" Configuring a Dancer 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 \fBdance()\fR method. .PP Other ways are possible, you can write all your setting calls in the file `appdir/config.yml'. For this, you must have installed the \s-1YAML\s0 module, and of course, write the conffile in \s-1YAML.\s0 .PP That's better than the first option, but it's still not perfect as you can't switch easily from an environment to another without rewriting the config.yml file. .PP The better 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, it will be 'development'). .PP Note that you can change the running environment using the \-\-environment command line 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 .SS "load" .IX Subsection "load" You can use the load method to include additional routes into your application: .PP .Vb 3 \& get \*(Aq/go/:value\*(Aq, sub { \& # foo \& }; \& \& load \*(Aqmore_routes.pl\*(Aq; \& \& # then, in the file more_routes.pl: \& get \*(Aq/yes\*(Aq, sub { \& \*(Aqorly?\*(Aq; \& }; .Ve .PP \&\fBload\fR is just a wrapper for \fBrequire\fR, but you can also specify a list of routes files: .PP .Vb 1 \& load \*(Aqlogin_routes.pl\*(Aq, \*(Aqsession_routes.pl\*(Aq, \*(Aqmisc_routes.pl\*(Aq; .Ve .SS "Accessing configuration data" .IX Subsection "Accessing configuration data" A Dancer 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 .SH "Importing just the syntax" .IX Header "Importing just the syntax" If you want to use more complex file hierarchies, you can import just the syntax of Dancer. .PP .Vb 1 \& package App; \& \& use Dancer; # App may contain generic routes \& use App::User::Routes; # user\-related routes .Ve .PP Then in App/User/Routes.pm: .PP .Vb 1 \& use Dancer \*(Aq:syntax\*(Aq; \& \& get \*(Aq/user/view/:id\*(Aq => sub { \& ... \& }; .Ve .SH "LOGGING" .IX Header "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.yml .PP .Vb 1 \& logger: \*(Aqfile\*(Aq .Ve .PP Then you can choose which kind of messages you want to actually log: .PP .Vb 4 \& log: \*(Aqdebug\*(Aq # will log debug, warning, error and info messages \& log: \*(Aqinfo\*(Aq # will log info, warning and error messages \& log: \*(Aqwarning\*(Aq # will log warning and error messages \& log: \*(Aqerror\*(Aq # will log error messages .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 debug, info, warning and error functions. For instance: .PP .Vb 1 \& debug "This is a debug message"; .Ve .SH "USING TEMPLATES" .IX Header "USING TEMPLATES" .SH "VIEWS" .IX Header "VIEWS" 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 (Dancer::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 Dancer::Template::TemplateToolkit. If you do so, you'll also have to import the Template module in your application code. Note that Dancer configures the Template::Toolkit engine to use <% %> brackets instead of its default [% %] brackets, although you can change this in your config file. .PP All views must have a '.tt' extension. This may change in the future. .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 Dancer; \& 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 .SS "\s-1LAYOUTS\s0" .IX Subsection "LAYOUTS" 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 Dancer; \& 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 Dancer; \& set layout => \*(Aqmain\*(Aq; \& \& get \*(Aq/nolayout\*(Aq => sub { \& template \*(Aqsome_ajax_view\*(Aq, \& { tokens_var => "42" }, \& { layout => 0 }; \& }; .Ve .SH "STATIC FILES" .IX Header "STATIC FILES" .SS "\s-1STATIC DIRECTORY\s0" .IX Subsection "STATIC DIRECTORY" 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. .SS "\s-1STATIC FILE FROM A ROUTE HANDLER\s0" .IX Subsection "STATIC FILE FROM A ROUTE HANDLER" 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 "SETTINGS" .IX Header "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 \s-1YAML\s0 configuration file. Environment-specific settings can also be defined in environment-specific files (for instance, you might want extra logging in development). See the cookbook for examples. .PP See Dancer::Config for complete details about supported settings. .SH "SERIALIZERS" .IX Header "SERIALIZERS" When writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer 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 response that is a reference 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 Dancer; \& 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 a reference \- and a serializer is set, which is not the case by default \- Dancer 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. .SH "EXAMPLE" .IX Header "EXAMPLE" This is a possible webapp created with Dancer: .PP .Vb 1 \& #!/usr/bin/perl \& \& # make this script a webapp \& use Dancer; \& \& # declare routes/actions \& get \*(Aq/\*(Aq => sub { \& "Hello World"; \& }; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& "Hello ".param(\*(Aqname\*(Aq); \& }; \& \& # run the webserver \& Dancer\->dance; .Ve .SH "AUTHOR" .IX Header "AUTHOR" Dancer Core Developers .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" This software is copyright (c) 2010 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.