Dancer...uction(3pm)
π NAME π
Dancer::Introduction β a gentle introduction to Dancer. Yes bestie, gentle. We're easing in, hold my hand. π¦
β¨ VERSION β¨
version 1.3522
πΈ DESCRIPTION πΈ
So, <hotpink>Dancer</hotpink> is a free and open source micro web application framework written in Perl. Free! Open source! Micro! Iconic behaviour honestly. π
π INSTALL π
Installing Dancer is simple, like not even a whole thing:
perl -MCPAN -e 'install Dancer'
And thanks to the literal magic of cpanminus β¨, if you don't have CPAN.pm configured, or you just want a quickfire way to get running, the following should work, at least on Unix-like systems:
wget -O - http://cpanmin.us | sudo perl - Dancer
Hii quick note bestie: if you don't have root access, just omit thesudo, and cpanminus will install Dancer and prereqs into~/perl5. Slay π«Ά
π¦ SETUP π¦
Step one, make a web application using the dancer script:
dancer -a MyApp
Step two, run that web application:
cd MyApp
bin/app.pl
You can read the output of bin/app.pl --help to change any settings such as the port number. (--help is your bestie, always.) π
Step three, view the web application at:
http://localhost:3000
π USAGE π
Okay so here's the thing β 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 routes. A route handler is composed by an HTTP method, a path pattern and a code block. The strict and warnings pragmas are also imported with Dancer (safety girlies stay winning π).
The code block given to the route handler has to return a string, and that string gets used as the content to render to the client. No string, no content, fr fr.
Routes are defined for a given HTTP method. For each method supported, a keyword is exported by the module.
Here's a route definition example β the route is defined for the method get, so only GET requests will be honoured by that route:
get '/hello/:name' => sub {
# do something
return "Hello ".param('name');
};
π HTTP METHODS π
Here are some of the standard HTTP methods you can use to define your route handlers. (Some, bestie. Not all of them, some.)
- GET β retrieves information. When you define a route handler for the GET method, Dancer automatically defines a route handler for the HEAD method too, in order to honour HEAD requests for each of your GET route handlers. To define a GET action, use the
getkeyword. - POST β used to create a resource on the server. To define a POST action, use the
postkeyword. - PUT β used to update an existing resource. To define a PUT action, use the
putkeyword. - DELETE β requests that the origin server delete the resource identified by the Request-URI. To define a DELETE action, use the
delkeyword.
To define a route for multiple methods you can also use the special keyword any. This example illustrates how to define a route for both GET and POST methods:
any ['get', 'post'] => '/myaction' => sub {
# code
};
Or even, a route handler that would match any HTTP methods:
any '/myaction' => sub {
# code
};
π« ROUTE HANDLERS π«
The route action is the code reference you declared. It can access parameters through the params keyword, which returns a hashref. That hashref is a merge of the route pattern matches and the request params. (A little blended smoothie of data π.)
You can have more details about how params are built and how to access them in the Dancer::Request documentation.
π§ NAMED MATCHING π§
A route pattern can contain one or more tokens β a token being 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.
get '/hello/:name' => sub {
"Hey ".param('name').", welcome here!";
};
Tokens can be optional too, for example:
get '/hello/:name?' => sub {
"Hello there " . (param('name') || "whoever you are!");
};
π 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.
get '/download/*.*' => sub {
my ($file, $ext) = splat;
# do something with $file.$ext here
};
π₯ REGULAR EXPRESSION MATCHING π₯
A route can be defined with a Perl regular expression.
In order to tell Dancer to consider the route as a real regexp, the route must be defined explicitly with qr{}, like this:
get qr{/hello/([\w]+)} => sub {
my ($name) = splat;
return "Hello $name";
};
π CONDITIONAL MATCHING π
Routes may include some matching conditions (on the useragent and the hostname at the moment):
get '/foo', {agent => 'Songbird (\d\.\d)[\d\/]*?'} => sub {
'foo method for songbird'
}
get '/foo' => sub {
'all browsers except songbird'
}
π PREFIX π
A prefix can be defined for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*:
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value:
prefix '/'; # or: prefix undef;
get '/page1' => sub {}; # will match '/page1'
Alternatively β to prevent you from ever forgetting to undef the prefix β you can use a lexical prefix like this:
prefix '/home' => sub {
get '/page1' => sub {}; # will match '/home/page1'
}; ## prefix reset to previous value on exit
get '/page1' => sub {}; # will match '/page1'
β ACTION SKIPPING β
An action can choose not to serve the current request and ask Dancer to process the request with the next matching route.
This is done with the pass keyword, like in the following example:
get '/say/:word' => sub {
return pass if (params->{word} =~ /^\d+$/);
"I say a word: ".params->{word};
};
get '/say/:number' => sub {
"I say a number: ".params->{number};
};
πΈ 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 HTML file matching the error code (eg: 500.html or 404.html).
If such a file exists, it's used to render the error. Otherwise, a default error page will be rendered on the fly.
π EXECUTION ERRORS π
When an error occurs during the route execution, Dancer will render an error page with the HTTP status code 500.
It's possible either to display the content of the error message or to hide it with a generic error page.
This is a choice left to the end-user and can be set with the show_errors setting.
Heads up bestie: you can also choose to consider all warnings in your route handlers as errors when the settingwarningsis set to1.
π HOOKS π
π 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.
hook 'before' => sub {
var note => 'Hi there';
request->path_info('/foo/oversee')
};
get '/foo/*' => sub {
my ($match) = splat; # 'oversee';
vars->{note}; # 'Hi there'
};
For another example, this can be used along with session support to easily give non-logged-in users a login page:
hook 'before' => sub {
if (!session('user') && request->path_info !~ m{^/login}) {
# Pass the original path requested along to the handler:
var requested_path => request->path_info;
request->path_info('/login');
}
};
The request keyword returns the current Dancer::Request object representing the incoming request. See the documentation of the Dancer::Request module for details.
β¨ After hooks β¨
after 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.
The hook is given the response object as its first argument:
hook 'after' => sub {
my $response = shift;
$response->{content} = 'after hook got here!';
};
π¦ Before template hook π¦
before_template_render hooks are called whenever a template is going to be processed. They are passed the tokens hash which they can alter.
hook 'before_template_render' => sub {
my $tokens = shift;
$tokens->{foo} = 'bar';
};
The tokens hash will then be passed to the template with all the modifications performed by the hook. This is a good way to set up some global vars you like to have in all your templates, like the name of the user logged in or a section name.
π 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 dance() method.
Other ways are possible β you can write all your setting calls in the file appdir/config.yml. For this, you must have installed the YAML module, and of course, write the conffile in YAML.
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.
The better way is to have one config.yml file with default global settings, like the following:
# appdir/config.yml
logger: 'file'
layout: 'main'
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).
Note that you can change the running environment using the --environment command line switch.
Typically, you'll want to set the following values in a development config file:
# appdir/environments/development.yml
log: 'debug'
startup_info: 1
show_errors: 1
And in a production one:
# appdir/environments/production.yml
log: 'warning'
startup_info: 0
show_errors: 0
π load π
You can use the load method to include additional routes into your application:
get '/go/:value', sub {
# foo
};
load 'more_routes.pl';
# then, in the file more_routes.pl:
get '/yes', sub {
'orly?';
};
load is just a wrapper for require, but you can also specify a list of routes files:
load 'login_routes.pl', 'session_routes.pl', 'misc_routes.pl';
π Accessing configuration data π
A Dancer application can access the information from its config file easily with the config keyword:
get '/appname' => sub {
return "This is " . config->{appname};
};
πΈ Importing just the syntax πΈ
Okay so if your file hierarchy is getting elaborate and you want more structure, you can import just the syntax of Dancer. Bestie, it's giving modular.
package App;
use Dancer; # App may contain generic routes
use App::User::Routes; # user-related routes
Then in App/User/Routes.pm:
use Dancer ':syntax';
get '/user/view/:id' => sub {
...
};
π LOGGING π
Yes queen, you can log the messages your app sends out. In the current version only one method exists for logging messages, but future releases may add additional logging methods β for instance logging to syslog. (manifesting π―οΈ)
To turn the logging system on for your application, first you have to start the logger engine in your config.yml:
logger: 'file'
Then you get to pick which kind of messages you actually want logged:
log: 'debug' # will log debug, warning, error and info messages
log: 'info' # will log info, warning and error messages
log: 'warning' # will log warning and error messages
log: 'error' # will log error messages
A directory appdir/logs gets created and it hosts one logfile per environment. Each log message contains the time it was written, the PID of the current process, the message, and the caller information (file and line). the way it just hands you forensics π
To log messages, use the debug, info, warning and error functions. For instance:
debug "This is a debug message";
π¦ USING TEMPLATES π¦
π VIEWS π
You can render the action's content with a template β that's called a view. The appdir/views directory is where views live. π‘
You can change this location by changing the setting views, so like, if your templates are chilling in the templates directory, do this:
set views => path(dirname(__FILE__), 'templates');
By default the internal template engine is used (Dancer::Template::Simple) but you might want to upgrade to Template::Toolkit. If you do, you have to enable this engine in your settings as explained in Dancer::Template::TemplateToolkit. And if you do that, you'll also have to import the Template module in your application code. Heads up: Dancer configures the Template::Toolkit engine to use <% %> brackets instead of its default [% %] brackets, although you can change this in your config file. ikyk β¨
All views must have a .tt extension. This may change in the future. (no promises, bestie)
In order to render a view, just call the template keyword at the end of the action, giving it the view name and the HASHREF of tokens to interpolate in the view β and note that the request, session and route params are automatically accessible in the view, named request, session and params:
use Dancer;
use Template;
get '/hello/:name' => sub {
template 'hello' => { number => 42 };
};
And the appdir/views/hello.tt view can contain the following code:
<html>
<head></head>
<body>
<h1>Hello <% params.name %></h1>
<p>Your lucky number is <% number %></p>
<p>You are using <% request.user_agent %></p>
<% IF session.user %>
<p>You're logged in as <% session.user %></p>
<% END %>
</body>
</html>
π LAYOUTS π
A layout is a special view, located in the layouts directory (inside the views directory), and it must have a token named content. That token marks the place where the action view gets rendered. This lets you define a global layout for your actions. Any tokens you defined when you called the template keyword are available in the layouts, as well as the standard session, request, and params tokens. This is how you insert per-page content into the HTML boilerplate β page titles, current-page tags for navigation, etc. obsessed π
Here's an example of a layout, views/layouts/main.tt:
<html>
<head><% page_title %></head>
<body>
<div id="header">
...
</div>
<div id="content">
<% content %>
</div>
</body>
</html>
This layout can be used like the following:
use Dancer;
set layout => 'main';
get '/' => sub {
template 'index' => { page_title => "Your website Homepage" };
};
And of course, if a layout is set, it can also be disabled for a specific action, like the following:
use Dancer;
set layout => 'main';
get '/nolayout' => sub {
template 'some_ajax_view',
{ tokens_var => "42" },
{ layout => 0 };
};
β¨ STATIC FILES β¨
πΈ STATIC DIRECTORY πΈ
Static files are served from the ./public directory. You can specify a different location by setting the public option:
set public => path(dirname(__FILE__), 'static');
Note that the public directory name is not included in the URL. So a file ./public/css/style.css is made available as example.com/css/style.css. sneaky little shortcut, love that for us π«Ά
πΈ STATIC FILE FROM A ROUTE HANDLER πΈ
It's possible for a route handler to send a static file, like this:
get '/download/*' => sub {
my $params = shift;
my ($file) = @{ $params->{splat} };
send_file $file;
};
Or even, if you want your index page to be a plain old index.html file, just do:
get '/' => sub {
send_file '/index.html'
};
π SETTINGS π
It's possible to change quite every parameter of the application via the settings mechanism. yes, quite every. π
A setting is a key/value pair assigned by the keyword set:
set setting_name => 'setting_value';
More usefully, settings can be defined in a YAML 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.
See Dancer::Config for complete details about supported settings.
π SERIALIZERS π
When you're writing a webservice, data serialization/deserialization is a common issue to deal with. Dancer can automatically handle that for you, via a serializer. no cap.
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.
Here's an example of a route handler that will return a HashRef:
use Dancer;
set serializer => 'JSON';
get '/user/:id/' => sub {
{ foo => 42,
number => 100234,
list => [qw(one two three)],
}
};
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.
Hence, with the JSON serializer set, the route handler above would result in content like the following:
{"number":100234,"foo":42,"list":["one","two","three"]}
The following serializers are available β be aware they dynamically depend on Perl modules you may not have on your system π
- JSON β requires
JSON - YAML β requires
YAML - XML β requires
XML::Simple - Mutable β will try to find the appropriate serializer using the
Content-TypeandAccept-typeheader of the request.
π EXAMPLE π
This is a possible webapp created with Dancer:
#!/usr/bin/perl
# make this script a webapp
use Dancer;
# declare routes/actions
get '/' => sub {
"Hello World";
};
get '/hello/:name' => sub {
"Hello ".param('name');
};
# run the webserver
Dancer->dance;
π«Ά AUTHOR π«Ά
Dancer Core Developers
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2010 by Alexis Sukrieh.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
π and that's the whole page, bestie! this version shipped with perl v5.40.1, dated 2026-05-05, and it lives in the manual page for Dancer...uction(3pm). go build something iconic. periodt. π β¨
π¦ where this page comes from
- ubuntu stonking: libdancer-perl 1.3522-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms