Dancer(3pm)

๐Ÿ’ƒ Dancer โ€” the Dancer(3pm) manual page, bestie edition ๐ŸŽ€

okay so. you found Dancer(3pm). it's a Perl thing. it's the Perl thing if you want a web app without selling your soul to a giant framework. let's go ๐Ÿ’–


โœจ NAME โœจ

Dancer โ€” lightweight yet powerful web application framework

like, it's small. but also it does EVERYTHING. both things can be true. ๐Ÿ’…


๐Ÿท๏ธ VERSION ๐Ÿท๏ธ

version 1.3522


๐ŸŒธ SYNOPSIS ๐ŸŒธ

ok so here's the whole entire vibe in like eight lines:

#!/usr/bin/perl
use Dancer;

get '/hello/:name' => sub {
    return "Why, hello there " . param('name');
};

dance;

that's it. that's a real, working, functional web app. no cap. ๐Ÿ”ฅ

and that's literally the entire point of Dancer โ€” a basic but fully functional web app, written by hand, in a handful of lines.

want more examples and want to be up and running fast? go read Dancer::Introduction and Dancer::Cookbook. those are your besties for getting started. and if you wanna actually put your app out into the world, Dancer::Deployment has the deployment tea. ๐Ÿซ–


๐Ÿ’œ DESCRIPTION ๐Ÿ’œ

so here's the thing about Dancer, bestie: it's a web application framework that was designed to be as effortless as possible for you, the developer. it handles all the boring bits โ€” as easily as possible โ€” while ALSO staying out of your way and letting you get on with writing your actual code. it's giving "supportive friend who never makes it about themselves." ๐Ÿซถ

Dancer aims to be the simplest way to write web applications. and then โ€” the way that it scales? iconic:

  • a very simple, lightweight web service that's just a few lines of code in a single file ๐Ÿ‘‘
  • all the way up to a more complex, fully-fledged web application with session support, templates for views and layouts, etc. โœจ

if you don't wanna be out here writing CGI scripts by hand, and you've looked at Catalyst and gone "girl that's too big and too cumbersome for my project" โ€” Dancer is literally what you need.

Dancer has few pre-requisites, so your Dancer webapps will be easy to deploy. no dependency hell, we don't do that here. ๐Ÿ™…

and the deployment options?? versatile. Dancer apps can run with:

  • an embedded web server โ€” great for easy testing ๐Ÿงช
  • PSGI/Plack โ€” great for easy deployment in a whole variety of webserver environments ๐ŸŒˆ

๐Ÿ“š MORE DOCUMENTATION ๐Ÿ“š

k so this doc you're reading right now? it describes all the exported symbols of Dancer. it's the reference, the whole menu.

if you want a quick start guide to actually discover the framework, you want Dancer::Introduction, or Dancer::Tutorial if you learn by example (which, same, honestly ๐Ÿฆ‹).

if you want specific examples of code for real-life problems โ€” like, actual problems you'd actually have โ€” go see Dancer::Cookbook. ๐Ÿ“

if you want to see configuration examples of different deployment solutions involving Dancer and Plack, that's Dancer::Deployment.

and you can find out more about the many useful plugins available for Dancer in Dancer::Plugins. there are so many. obsessed.


๐Ÿ‘‘ DANCER 2 ๐Ÿ‘‘

ok important announcement time, bestie. ๐Ÿ“ข

this right here is the original version of Dancer, and it is now in maintenance mode. let's break down what that actually means, no sugarcoating:

  • it will not receive significant new features
  • it will continue to receive bugfixes and security fixes
  • no "end of life" date has been set
  • it's expected that this version of Dancer will continue to receive bugfixes and security fixes for quite some time yet

so she's not dying, she's justโ€ฆ chilling. ๐Ÿง˜

However โ€” and listen โ€” you should consider migrating to Dancer2 instead when you can, and you are advised to use Dancer2 for newly-started apps. like, if it's a fresh app, just go Dancer2. fr fr.

Dancer2 is mostly backwards compatible, but it's been re-written from the ground up to be more maintainable and extensible, and it is the future of Dancer. ๐ŸŒŸ

Dancer2::Manual::Migration covers the changes you should be aware of when migrating an existing Dancer 1 powered app to Dancer 2. read that before you yolo the upgrade. ๐Ÿ™ˆ


๐Ÿ“ฆ EXPORTS ๐Ÿ“ฆ

by default, use Dancer exports all the functions below, PLUS it sets up your app. two-for-one. ๐Ÿ’…

you can control the exporting through the normal Exporter mechanism. for example:

# Just export the route controllers
use Dancer qw(get post put patch del);

# Export everything but pass to avoid clashing with Test::More
use Test::More;
use Dancer qw(!pass);

please note โ€” and this one's important โ€” the utf8 and strict pragmas are exported by this module. they come free with the vibes.

by default, the warnings pragma will also be exported, meaning your app/script will be running under use warnings. if you do not want this, set the global_warnings setting to a false value.

there are also some special tags to control exports and behaviour. let's meet them ๐ŸŽ€


๐Ÿฆ‹ :moose ๐Ÿฆ‹

this will export everything except functions which clash with Moose. currently these are after and before.


๐Ÿฆ‹ :syntax ๐Ÿฆ‹

this tells Dancer to just export symbols and not set up your app.

most useful for writing Dancer code outside of your main route handler. iykyk.


๐Ÿฆ‹ :tests ๐Ÿฆ‹

this will export everything except functions which clash with commonly used testing modules. currently these are pass.

it can be combined with other export pragmas. for example, while testing...

use Test::More;
use Dancer qw(:syntax :tests);

# Test::Most also exports "set" and "any"
use Test::Most;
use Dancer qw(:syntax :tests !set !any);

# Alternatively, if you want to use Dancer's set and any...
use Test::Most qw(!set !any);
use Dancer qw(:syntax :tests);

๐Ÿฆ‹ :script ๐Ÿฆ‹

this will export all the keywords, load the configuration, and will not try to parse command-line arguments via Dancer::GetOpt.

this is useful when you want to use your Dancer application from a script:

use MyApp;
use Dancer ':script';
MyApp::schema('DBSchema')->deploy();
โš ๏ธ note that using :script will disable command-line parsing for all subsequent invocations of use Dancer โ€” such that you don't have to use :script for each and every module to make sure the command-line arguments don't get stolen by Dancer. one and done, bestie.

๐Ÿฆ‹ !keyword ๐Ÿฆ‹

if you want to simply prevent Dancer from exporting specific keywords โ€” maybe you plan to implement them yourself in a different way, or you don't plan to use them and they clash with another module you're loading โ€” you can simply exclude them:

use Dancer qw(!session);

the above would import all keywords as normal, with the exception of session. eat your heart out, session. ๐Ÿšซ


๐Ÿ”ง FUNCTIONS ๐Ÿ”ง


after

Deprecated โ€” see the "after" hook.

(rip bestie, she's deprecated ๐Ÿ’€)


any

defines a route for multiple HTTP methods at once:

any ['get', 'post'] => '/myaction' => sub {
    # code
};

or even, a route handler that would match any HTTP methods:

any '/myaction' => sub {
    # code
};

one route, every method, no drama. ๐Ÿ‘‘


before

Deprecated โ€” see the "before" hook.


before_template

Deprecated โ€” see the "before_template" hook.


๐Ÿช cookies ๐Ÿช

accesses cookies values. it returns a HashRef of Dancer::Cookie objects:

get '/some_action' => sub {
    my $cookie = cookies->{name};
    return $cookie->value;
};

in the case you have stored something other than a Scalar in your cookie:

get '/some_action' => sub {
    my $cookie = cookies->{oauth};
    my %values = $cookie->value;
    return ($values{token}, $values{token_secret});
};

see, she can do hashrefs too. versatile queen. ๐Ÿ’–


accesses a cookie value (or sets it). note that this method will eventually be preferred over set_cookie. moving on up, honestly. ๐Ÿ“ˆ

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

if your cookie value is a key/value URI string, like

token=ABC&user=foo

cookie will only return the first part (token=ABC) if called in scalar context. use list context to fetch them all:

my @values = cookie "name";
โš ๏ธ and note that if the client has sent more than one cookie with the same value, the one returned will be the last one seen. this should only happen if you have set multiple cookies with the same name but different paths. soโ€ฆ don't do that. ๐Ÿ™ˆ

โš™๏ธ config โš™๏ธ

accesses the configuration of the application:

get '/appname' => sub {
    return "This is " . config->{appname};
};

your config, your rules. โœจ


๐Ÿ“„ content_type ๐Ÿ“„

sets the content-type rendered, for the current route handler:

get '/cat/:txtfile' => sub {
    content_type 'text/plain';

    # here we can dump the contents of param('txtfile')
};

you can use abbreviations for content types. for instance:

get '/svg/:id' => sub {
    content_type 'svg';

    # here we can dump the image with id param('id')
};
โš ๏ธ note that if you want to change the default content-type for every route, you have to change the content_type setting instead. per-route vs. global, know the difference bestie.

๐Ÿ’ƒ dance ๐Ÿ’ƒ

alias for the start keyword.

(she ate and left no crumbs, by just calling start.)


๐Ÿ”ข dancer_version ๐Ÿ”ข

returns the version of Dancer. if you need the major version, do something like:

int(dancer_version);

๐Ÿ› debug ๐Ÿ›

logs a message of debug level:

debug "This is a debug message";

see Dancer::Logger for details on how to configure where log messages go. ๐Ÿ“


๐Ÿ“ dirname ๐Ÿ“

returns the dirname of the path given:

my $dir = dirname($some_path);

๐Ÿงš engine ๐Ÿงš

given a namespace, returns the current engine object:

my $template_engine = engine 'template';
my $html = $template_engine->apply_renderer(...);
$template_engine->apply_layout($html);

โŒ error โŒ

logs a message of error level:

error "This is an error message";

see Dancer::Logger for details on how to configure where log messages go. ๐Ÿ“


๐Ÿคฅ false ๐Ÿคฅ

constant that returns a false value (0).


โžก๏ธ forward โžก๏ธ

runs an internal redirect of the current request to another request. this helps you avoid having to redirect the user using HTTP and set another request to your application.

it effectively lets you chain routes together in a clean manner. ๐Ÿ”—

get '/demo/articles/:article_id' => sub {

    # you'll have to implement this next sub yourself :)
    change_the_main_database_to_demo();

    forward "/articles/" . params->{article_id};
};

in the above example, the users that reach /demo/articles/30 will actually reach /articles/30 โ€” but we've changed the database to demo before. sneaky. iconic.

this is pretty cool because it lets us retain our paths and offer a demo database by merely going to /demo/.... โœจ

you'll notice that in the example we didn't indicate whether it was GET or POST. that is because forward chains the same type of route the user reached. if it was a GET, it will remain a GET. (but if you do need to change the method, you can do so; read on below for details.)

โš ๏ธ WARNING : using forward will not preserve session data set on the forwarding rule.
โš ๏ธ WARNING : issuing a forward immediately exits the current route, and performs the forward. thus, any code after a forward is ignored, until the end of the route. e.g.
get '/foo/:article_id' => sub {
    if ($condition) {
        forward "/articles/" . params->{article_id};
        # The following code is never executed
        do_stuff();
    }

    more_stuff();
};

so it's not necessary anymore to use return with forward. ๐Ÿ‘‘

note that forward doesn't parse GET arguments. so, you can't use something like:

 return forward '/home?authorized=1';

but forward supports an optional HashRef with parameters to be added to the actual parameters:

 return forward '/home', { authorized => 1 };

finally, you can add some more options to the forward 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. ๐Ÿซฃ

return forward '/home', { auth => 1 }, { method => 'POST' };

๐Ÿงš from_dumper ($structure)

Takes a Data::Dumper structure and deserializes it back to life. โœจ

๐ŸŒธ from_json ($structure, \%options)

Deserializes a JSON structure. You can hand it optional args too โ€” those are just straight-up valid JSON arguments that change how the default JSON::from_json function behaves.

โš ๏ธ Compatibility notice, bestie, listen up: from_json changed in 1.3002 to take a hashref as options, instead of a hash. If your old code is acting up, that's why. ๐Ÿ˜ญ

๐Ÿฆ‹ from_yaml ($structure)

Deserializes a YAML structure. That's it, that's the whole job. ๐Ÿ’œ

๐ŸŽ€ from_xml ($structure, %options)

Deserializes an XML structure. Can receive optional arguments โ€” and those arguments are valid XML::Simple arguments that change the behaviour of the default XML::Simple::XMLin function.

๐Ÿ‘‘ get

Defines a route for HTTP GET requests to the given path:

get '/' => sub {
    return "Hello world";
}
๐Ÿ’ก Note that a route to match HEAD requests is automatically created too. Like, free of charge. Slay.

๐Ÿ’… halt

Sets a response object with the content you give it.

When you use it as a return value from a filter, it breaks the execution flow and renders the response immediately:

hook before sub {
    if ($some_condition) {
        halt("Unauthorized");
        # This code is not executed :
        do_stuff();
    }
};

get '/' => sub {
    "hello there";
};
๐Ÿšจ WARNING : 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 return with halt. She does NOT wait around, periodt.

๐ŸŒˆ headers

Adds custom headers to responses:

get '/send/headers', sub {
    headers 'X-Foo' => 'bar', X-Bar => 'foo';
}

adds a custom header to response:

get '/send/header', sub {
    header 'x-my-header' => 'shazam!';
}
๐Ÿ™ˆ Note that it will overwrite the old value of the header, if any. To avoid that, see push_header. Don't say I didn't warn you.

๐Ÿ’– push_header

Do the same as header, but allow for multiple headers with the same name:

get '/send/header', sub {
    push_header 'x-my-header' => '1';
    push_header 'x-my-header' => '2';
    will result in two headers "x-my-header" in the response
}

๐Ÿงš hook

Adds a hook at some position. For example :

hook before_serializer => sub {
  my $response = shift;
  $response->content->{generated_at} = localtime();
};

There can be multiple hooks assigned to a given position, and each will be executed in order. Note that all hooks are always called, even if they are defined in a different package loaded via load_app. No hiding, no skipping. ๐Ÿ‘‘

(For details on how to register new hooks from within plugins, see Dancer::Hook.)

Supported before hooks (in order of execution):


๐ŸŽ€ before_deserializer

This hook receives no arguments.

hook before_deserializer => sub {
  ...
};

๐ŸŽ€ before_file_render

This hook receives as argument the path of the file to render.

hook before_file_render => sub {
  my $path = shift;
  ...
};

๐ŸŽ€ before_error_init

This hook receives as argument a Dancer::Error object.

hook before_error_init => sub {
  my $error = shift;
  ...
};

๐ŸŽ€ before_error_render

This hook receives as argument a Dancer::Error object.

hook before_error_render => sub {
  my $error = shift;
};

๐ŸŽ€ before

This hook receives one argument, the route being executed (a Dancer::Route object).

hook before => sub {
  my $route_handler = shift;
  ...
};

it is equivalent to the deprecated

before sub {
  ...
};

๐ŸŽ€ before_template_render

This is an alias to 'before_template'.

This hook receives as argument a HashRef containing the tokens that will be passed to the template. You can use it to add more tokens, or delete some specific token.

hook before_template_render => sub {
  my $tokens = shift;
  delete $tokens->{user};
  $tokens->{time} = localtime;
};

is equivalent to

hook before_template => sub {
  my $tokens = shift;
  delete $tokens->{user};
  $tokens->{time} = localtime;
};

๐ŸŽ€ before_layout_render

This hook receives two arguments. The first one is a HashRef containing the tokens. The second is a ScalarRef representing the content of the template.

hook before_layout_render => sub {
  my ($tokens, $html_ref) = @_;
  ...
};

๐ŸŽ€ before_serializer

This hook receives as argument a Dancer::Response object.

hook before_serializer => sub {
  my $response = shift;
  $response->content->{start_time} = time();
};

Supported after hooks (in order of execution):


๐Ÿฆ‹ after_deserializer

This hook receives no arguments.

hook after_deserializer => sub {
  ...
};

๐Ÿฆ‹ after_file_render

This hook receives as argument a Dancer::Response object.

hook after_file_render => sub {
  my $response = shift;
};

๐Ÿฆ‹ after_template_render

This hook receives as argument a ScalarRef representing the content generated by the template.

hook after_template_render => sub {
  my $html_ref = shift;
};

๐Ÿฆ‹ after_layout_render

This hook receives as argument a ScalarRef representing the content generated by the layout

hook after_layout_render => sub {
  my $html_ref = shift;
};

๐Ÿฆ‹ after

This is an alias for after.

This hook runs after a request has been processed, but before the response is sent. Very "behind the scenes but make it fashion" of it. โœจ

It receives a Dancer::Response object, which it can modify if it needs to make changes to the response which is about to be sent.

hook after => sub {
  my $response = shift;
};

This is equivalent to the deprecated

after sub {
  my $response = shift;
};

๐Ÿฆ‹ after_error_render

This hook receives as argument a Dancer::Response object.

hook after_error_render => sub {
  my $response = shift;
};

๐ŸŒˆ on_handler_exception

This hook is called when an exception has been caught, at the handler level, just before creating and rendering Dancer::Error. This hook receives as argument a Dancer::Exception object.

hook on_handler_exception => sub {
  my $exception = shift;
};

๐ŸŒˆ on_reset_state

This hook is called when global state is reset to process a new request. It receives a boolean value that indicates whether the reset was called as part of a forwarded request.

hook on_reset_state => sub {
  my $is_forward = shift;
};

๐ŸŒˆ on_route_exception

This hook is called when an exception has been caught, at the route level, just before rethrowing it higher. This hook receives the exception as argument. It can be a Dancer::Exception, or a string, or whatever was used to die.

hook on_route_exception => sub {
  my $exception = shift;
};

๐Ÿ“ info

Logs a message of info level:

info "This is a info message";

See Dancer::Logger for details on how to configure where log messages go. ๐Ÿ“

๐Ÿ“ layout

This method is deprecated. Use set:

set layout => 'user';

๐Ÿ“ logger

Deprecated. Use set logger => 'console' to change current logger engine.

๐Ÿง load

Loads one or more perl scripts in the current application's namespace. Syntactic sugar around Perl's require:

load 'UserActions.pl', 'AdminActions.pl';

๐Ÿง load_app

Loads a Dancer package. This method sets the libdir to the current ./lib directory:

# if we have lib/Webapp.pm, we can load it like:
load_app 'Webapp';
# or with options
load_app 'Forum', prefix => '/forum', settings => {foo => 'bar'};
โš ๏ธ Note that the package loaded using load_app must import Dancer with the :syntax option. Non-negotiable, bestie.

To load multiple apps repeat load_app:

load_app 'one';
load_app 'two';

The old way of loading multiple apps in one go (load_app 'one', 'two';) is deprecated. It's giving 2011. ๐Ÿ’€

๐Ÿ’œ mime

Shortcut to access the instance object of Dancer::MIME. You should read the Dancer::MIME documentation for full details, but the most commonly-used methods are summarized below:

# set a new mime type
mime->add_type( foo => 'text/foo' );

# set a mime type alias
mime->add_alias( f => 'foo' );

# get mime type for an alias
my $m = mime->for_name( 'f' );

# 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 => 'text/plain';

๐ŸŒธ params

This method should be called from a route handler. It's an alias for the Dancer::Request params accessor. In list context it returns a list of key/value pair of all defined parameters. In scalar context it returns a hash reference instead. Check param below to access quickly to a single parameter value. ๐Ÿซถ

๐ŸŒธ param

This method should be called from a route handler. This method is an accessor to the parameters hash table.

post '/login' => sub {
    my $username = param "user";
    my $password = param "pass";
    # ...
}

๐ŸŒธ param_array

This method should be called from a route handler. Like param, but always returns the parameter value or values as a list. Returns the number of values in scalar context.

# if request is '/tickets?tag=open&tag=closed&order=desc'...
get '/tickets' => sub {
    my @tags = param_array 'tag';  # ( 'open', 'closed' )
    my $tags = param 'tag';        # array ref

    my @order = param_array 'order';  # ( 'desc' )
    my $order = param 'order';        # 'desc'
};

๐Ÿ’… pass

This method should be called from a route handler. Tells Dancer to pass the processing of the request to the next matching route.

๐Ÿšจ WARNING : Issuing a pass immediately exits the current route, and performs the pass. Thus, any code after a pass is ignored until the end of the route. So it's not necessary any more to use return with pass. She's gone, she said what she said. ๐Ÿ‘‹

right, so pass(...) looking like this in real life โœจ

get '/some/route' => sub {
    if (...) {
        # we want to let the next matching route handler process this one
        pass(...);
        # This code will be ignored
        do_stuff();
    }
};

๐Ÿ’… patch

Defines a route for HTTP PATCH requests to the given URL:

patch '/resource' => sub { ... };

ngl bestie, PATCH is one of those relatively new, not-yet-common HTTP verbs ๐Ÿ˜ญ โ€” it's meant to work like a "partial-PUT", transferring just the changes instead of the whole thing. Want the receipts? Go read RFC5789 at http://tools.ietf.org/html/rfc5789 ๐Ÿ“œ.

โš ๏ธ Big heads-up: if you run your app in standalone mode, PATCH requests will not reach your app unless you have a new version of HTTP::Server::Simple that accepts PATCH as a valid verb. The current version at time of writing, 0.44, does not. A pull request has been submitted to add this support, and you can find it at:

https://github.com/bestpractical/http-server-simple/pull/1


๐Ÿ›ค๏ธ path โ€” wait, path

Concatenates multiple paths together, and it literally does not care what operating system you're on ๐ŸŒˆ:

my $path = path(dirname($0), 'lib', 'File.pm');

It also normalizes (cleans) the path aesthetically โœจ. It does not verify that the path exists, so don't come for it when it doesn't. ๐Ÿซถ


๐Ÿ“ฎ post

Defines a route for HTTP POST requests to the given URL:

post '/' => sub {
    return "Hello world";
}

๐ŸŽ€ prefix

Defines a prefix 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 undef;
get '/page1' => sub {}; will match /page1

For a safer alternative you can use a lexical prefix like this ๐Ÿ‘‡

prefix '/home' => sub {
    ## Prefix is set to '/home' here

    get ...;
    get ...;
};
## prefix reset to the previous version here

This makes it possible to nest prefixes, which is honestly iconic โœจ:

prefix '/home' => sub {
    ## some routes

   prefix '/private' => sub {
      ## here we are under /home/private...

      ## some more routes
   };
   ## back to /home
};
## back to the root
๐Ÿšจ Notice: once you have a prefix set, do not add a caret to the regex:
prefix '/foo';
get qr{^/bar} => sub { ... } # BAD BAD BAD
get qr{/bar}  => sub { ... } # Good!

๐Ÿ—‘๏ธ del

Defines a route for HTTP DELETE requests to the given URL:

del '/resource' => sub { ... };

๐Ÿง options

Defines a route for HTTP OPTIONS requests to the given URL:

options '/resource' => sub { ... };

๐Ÿ“ค put

Defines a route for HTTP PUT requests to the given URL:

put '/resource' => sub { ... };

๐Ÿ” redirect

Generates an HTTP redirect (302) ๐Ÿ’ซ. You can either redirect to a completely different site, or stay within the application:

get '/twitter', sub {
    redirect 'http://twitter.com/me';
};

You can also force Dancer to return a specific 300-ish HTTP response code:

get '/old/:resource', sub {
    redirect '/new/'.params->{resource}, 301;
};
๐Ÿ’€ It is important to note that issuing a redirect by itself does not exit and redirect immediately. Redirection is deferred until after the current route or filter has been processed. To exit and redirect immediately, use the return function, e.g.
get '/restricted', sub {
    return redirect '/login' if accessDenied();
    return 'Welcome to the restricted section';
};

๐Ÿ–ผ๏ธ render_with_layout

Allows a handler to provide plain HTML (or other content), but have it rendered within the layout still.

๐Ÿšจ This method is DEPRECATED, and will be removed soon. Instead, you should be using the "engine" keyword:
get '/foo' => sub {
    # Do something which generates HTML directly (maybe using
    # HTML::Table::FromDatabase or something)
    my $content = ...;

    # get the template engine
    my $template_engine = engine 'template';

    # apply the layout (not the renderer), and return the result
    $template_engine->apply_layout($content)
};

It works very similarly to "template" in that you can pass tokens to be used in the layout, and/or options to control the way the layout is rendered ๐Ÿ‘‘. For instance, to use a custom layout:

render_with_layout $content, {}, { layout => 'layoutname' };

๐Ÿ“จ request

Returns a Dancer::Request object representing the current request ๐Ÿซถ.

See the Dancer::Request documentation for the methods you can call, for example:

request->referer;         # value of the HTTP referer header
request->remote_address;  # user's IP address
request->user_agent;      # User-Agent header value

๐Ÿ›‘ send_error

Returns an HTTP error. By default the HTTP code returned is 500:

get '/photo/:id' => sub {
    if (...) {
        send_error("Not allowed", 403);
    } else {
       # return content
    }
}
โš ๏ธ WARNING: Issuing a send_error immediately exits the current route, and performs the send_error. So like, any code after a send_error is ignored, all the way until the end of the route ๐Ÿ’€. Which means it's not necessary anymore to use "return" with send_error.
get '/some/route' => sub {
    if (...) {
        # we want to let the next matching route handler process this one
        send_error(..);
        # This code will be ignored
        do_stuff();
    }
};

๐Ÿ“ 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 public directory unless you use the "system_path" option (see below).

get '/download/:file' => sub {
    send_file(params->{file});
}
โš ๏ธ WARNING: Issuing a send_file immediately exits the current route, and performs the send_file. So any code after a send_file is ignored until the end of the route ๐Ÿ’€. So it's not necessary any more to use "return" with send_file.
get '/some/route' => sub {
    if (...) {
        # we want to let the next matching route handler process this one
        send_file(...);
        # This code will be ignored
        do_stuff();
    }
};

Send file supports streaming possibility using PSGI streaming โœจ. The server should support it, but normal streaming is supported on most, if not all.

get '/download/:file' => sub {
    send_file( params->{file}, streaming => 1 );
}

You can control what happens using callbacks ๐ŸŽ€.

First, "around_content" allows you to get the writer object and the chunk of content read, and then decide what to do with each chunk:

get '/download/:file' => sub {
    send_file(
        params->{file},
        streaming => 1,
        callbacks => {
            around_content => sub {
                my ( $writer, $chunk ) = @_;
                $writer->write("* $chunk");
            },
        },
    );
}

You can use "around" to all 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:

get '/download/:file' => sub {
    send_file(
        params->{file},
        streaming => 1,
        callbacks => {
            around => sub {
                my ( $writer, $content ) = @_;

                # we know it's a text file, so we'll just stream
                # line by line
                while ( my $line = <$content> ) {
                    $writer->write($line);
                }
            },
        },
    );
}

Or you could use "override" to control the entire streaming callback request ๐Ÿ‘‡

get '/download/:file' => sub {
    send_file(
        params->{file},
        streaming => 1,
        callbacks => {
            override => sub {
                my ( $respond, $response ) = @_;

                my $writer = $respond->( [ $newstatus, $newheaders ] );
                $writer->write("some line");
            },
        },
    );
}

You can also set the number of bytes that will be read at a time (the default being 42K bytes) using "bytes":

get '/download/:file' => sub {
    send_file(
        params->{file},
        streaming => 1,
        bytes     => 524288, # 512K
    );
};

The content-type will be set depending on the current MIME types definition (see "mime" if you want to define your own) ๐Ÿงš.

If your filename does not have an extension, or you need to force a specific mime type, you can pass it to "send_file" as follows:

send_file(params->{file}, content_type => 'image/png');

Also, you can use your aliases or file extension names on "content_type", like this:

send_file(params->{file}, content_type => 'png');

For files outside your public folder, you can use the "system_path" switch. Just bear in mind that its use needs caution, as it can be dangerous ๐Ÿ’€.

send_file('/etc/passwd', system_path => 1);

If you have your data in a scalar variable, "send_file" can be useful as well. Pass a reference to that scalar, and "send_file" will behave as if there were a file with that contents:

send_file( \$data, content_type => 'image/png' );
๐Ÿ™ˆ Note that Dancer is unable to guess the content type from the data contents. Therefore you might need to set the "content_type" properly. For this kind of usage an attribute named "filename" can be useful. It is used as the Content-Disposition header, to hint the browser about the filename it should use.
send_file( \$data, content_type => 'image/png'
                          filename     => 'onion.png' );

โš™๏ธ set

Defines a setting:

set something => 'value';

You can set more than one value at once ๐Ÿซถ:

set something => 'value', otherthing => 'othervalue';

๐Ÿ” setting

Returns the value of a given setting:

setting('something'); # 'value'

Creates or updates cookie values ๐Ÿ“:

get '/some_action' => sub {
    set_cookie name => 'value',
               expires => (time + 3600),
               domain  => '.foo.com';
};

In the example above, only 'name' and 'value' are mandatory โœจ.

You can also store more complex structure in your cookies:

           get '/some_auth' => sub {
               set_cookie oauth => {
                   token        => $twitter->request_token,
                   token_secret => $twitter->secret_token,
                   ...
               };
           };

okay so listen โ€” that HashRef is the absolute limit of complexity here. Every key in it has to be a Scalar. Storing references? Not gonna work, bestie, it just won't. ๐Ÿ˜ญ

For all the extra lil goodies you can set when you're making a cookie, go peep Dancer::Cookie.

๐Ÿ’€ heads up: this method is eventually getting deprecated in favor of the new cookie method. So like, use cookie if you can, iykyk.

๐Ÿซถ session

gives you access to everything sitting in the user's session (if there even is one, no shade).

It's also a setter, so you can stash stuff in the session with it:

    # getter example
    get '/user' => sub {
        if (session('user')) {
            return "Hello, ".session('user')->name;
        }
    };

    # setter example
    post '/user/login' => sub {
        ...
        if ($logged_in) {
            session user => $user;
        }
        ...
    };

Sometimes you gotta clear the whole thing out too, periodt:

    # destroy session
    get '/logout' => sub {
        ...
        session->destroy;
        ...
    };

And if you're ever like "wait what's the session ID rn", for literally any reason:

    my $id = session->id;

โœจ To actually USE sessions, you first have to turn session support on in one of the config files. The quick-and-dirty way is to add

    session: "YAML"

to config.yml. That's it, that's the whole thing.

For the full lore, see Dancer::Session. ๐Ÿ’–


๐ŸŒˆ splat

returns the list of captures you got from a route handler whose route pattern had wildcards:

    get '/file/*.*' => sub {
        my ($file, $extension) = splat;
        ...
    };

There's also the extensive splat (A.K.A. the "megasplat", iconic name, no notes) which lets you do way greedier matching โ€” you get it with two asterisks. The extra path gets broken down and handed back to you as an ArrayRef:

    get '/entry/*/tags/**' => sub {
        my ( $entry_id, $tags ) = splat;
        my @tags = @{$tags};
    };

And this is chef's kiss for chained actions:

    get '/team/*/**' => sub {
        my ($team) = splat;
        var team => $team;
        pass;
    };

    prefix '/team/*';

    get '/player/*' => sub {
        my ($player) = splat;

        # etc...
    };

    get '/score' => sub {
        return score_for( vars->{'team'} );
    };

๐Ÿ‘‘ start

Starts the application, or the standalone server โ€” depends on your deployment choices, so like, your call.

You should call this keyword at the very end of the script, once every single route is defined. At that point, Dancer takes over control. hand over the aux cord, she's driving now. ๐Ÿš—๐Ÿ’จ


๐ŸŽ€ status

Changes the status code that an action hands out. By default an action produces an "HTTP 200 OK" status code, meaning everything's fine and dandy:

    get '/download/:file' => {
        if (! -f params->{file}) {
            status 'not_found';
            return "File does not exist, unable to download";
        }
        # serving the file...
    };

See how in that example Dancer notices the status changed and renders the response accordingly? yeah. she's observant like that. ๐Ÿ’…

status takes either a numeric status code or its name in lower case, with underscores as separators for the blank spaces. The full list lives in "HTTP CODES" in Dancer::HTTP.


๐Ÿฆ‹ 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.

Here's a route handler returning the result of using template to build a response with your current template engine:

    get '/' => sub {
        ...
        return template 'some_view', { token => 'value'};
    };
โš ๏ธ ok so important: template just returns the content. So when you use it in a route handler and you want execution to stop right there, you gotta use return so your route handler actually returns the content. Don't forget, bestie. ๐Ÿ˜ญ

And since template just gives you back the rendered result, you can also use it for other templating tasks โ€” like generating emails, which is a whole vibe:

    post '/some/route' => sub {
        if (...) {
            email {
                to      => 'someone@example.com',
                from    => 'foo@example.com',
                subject => 'Hello there',
                msg     => template('emails/foo', { name => params->{name} }),
            };

            return template 'message_sent';
        } else {
            return template 'error';
        }
    };

Compatibility notice, and this is a whole saga: "template" was changed in version 1.3090 to immediately interrupt execution of a route handler and return the content, since it's typically used at the end of a route handler to return content. But that caused issues for some people who were using "template" to generate emails and stuff rather than accessing the template engine directly, so this change has been reverted in 1.3091. drama. resolved. moving on. ๐Ÿฟ

So the params go like this: 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.

For example, to disable the layout for one specific request:

    get '/' => sub {
        template 'index', {}, { layout => undef };
    };

Or to request a specific layout, of course:

    get '/user' => sub {
        template 'user', {}, { layout => 'user' };
    };

Some tokens get added to your template automatically: "perl_version", "dancer_version", "settings", "request", "params", "vars" and, if you have sessions enabled, "session". Go check Dancer::Template::Abstract for further details. โœจ


๐Ÿงš to_dumper ($structure)

Serializes a structure with Data::Dumper.


๐Ÿ’œ to_json ($structure, %options)

Serializes a structure to JSON. It can receive optional arguments. Those arguments are valid JSON arguments to change the behaviour of the default "JSON::to_json" function.

Compatibility notice: "to_json" changed in 1.3002 to take a hashref as options, instead of a hash. (yes. it's giving breaking change. we said what we said.)


๐ŸŒธ to_yaml ($structure)

Serializes a structure to YAML.


โญ to_xml ($structure, %options)

Serializes a structure to XML. It can receive optional arguments. Those arguments are valid XML::Simple arguments to change the behaviour of the default "XML::Simple::XMLout" function.


โœ… true

Constant that returns a true value (1).


๐Ÿ“ upload

Gives you access to file uploads. Any uploaded file is accessible as a Dancer::Request::Upload object. You can access all parsed uploads via:

    post '/some/route' => sub {
        my $file = upload('file_input_foo');
        # file is a Dancer::Request::Upload object
    };

If you named multiple inputs of type "file" with the same name, the upload keyword will return an Array of Dancer::Request::Upload objects:

    post '/some/route' => sub {
        my ($file1, $file2) = upload('files_input');
        # $file1 and $file2 are Dancer::Request::Upload objects
    };

You can also access the raw HashRef of parsed uploads through the current request object:

    post '/some/route' => sub {
        my $all_uploads = request->uploads;
        # $all_uploads->{'file_input_foo'} is a Dancer::Request::Upload object
        # $all_uploads->{'files_input'} is an ArrayRef of Dancer::Request::Upload objects
    };

And ngl you can also grab the filename of the upload you received via the params keyword:

    post '/some/route' => sub {
        # params->{'files_input'} is the filename of the file uploaded
    };

See Dancer::Request::Upload for all the deets about the interface it provides. ๐Ÿ’–


๐Ÿฆ„ uri_for

Returns a fully-qualified URI for the given path:

    get '/' => sub {
        redirect uri_for('/path');
        # can be something like: http://localhost:3000/path
    };

Querystring parameters can be provided by passing a hashref as a second param, and URL-encoding can be disabled via a third parameter:

    uri_for('/path', { foo => 'bar' }, 1);
    # would return e.g. http://localhost:3000/path?foo=bar

๐ŸŽฏ captures

Returns a reference to a copy of %+, if there are named captures in the route Regexp.

๐Ÿ’€ Named captures are a feature of Perl 5.10, and are not supported in earlier versions. old perl said no. ๐Ÿ˜ญ
    get qr{
        / (?<object> user   | ticket | comment )
        / (?<action> delete | find )
        / (?<id> \d+ )
        /?$
    }x
    , sub {
        my $value_for = captures;
        "i don't want to $$value_for{action} the $$value_for{object} $$value_for{id} !"
    };

๐Ÿซง var

Gives you an accessor for variables shared between filters and route handlers. Hand it a key/value pair and it sets a variable:

    hook before sub {
        var foo => 42;
    };

Later on, route handlers and other filters can read that variable:

    get '/path' => sub {
        my $foo = var 'foo';
        ...
    };

๐Ÿซง vars

Returns the HashRef of all the shared variables set during the filter/route chain with the "var" keyword:

    get '/path' => sub {
        if (vars->{foo} eq 42) {
            ...
        }
    };

๐Ÿ”” warning

Logs a warning message through the current logger engine:

    warning "This is a warning";

See Dancer::Logger for details on how to configure where your log messages actually go. ๐Ÿซถ


๐ŸŒŸ AUTHOR ๐ŸŒŸ

This module has been written by Alexis Sukrieh <sukria@cpan.org> and others โ€” see the AUTHORS file that comes with this distribution for details. legends only, fr fr. ๐Ÿ‘‘


๐Ÿ™ SOURCE CODE ๐Ÿ™

The source code for this module is hosted on GitHub at https://github.com/PerlDancer/Dancer. Feel free to fork the repository and submit pull requests! (See Dancer::Development for details on how to contribute.)

Also, why not watch the repo at https://github.com/PerlDancer/Dancer/toggle_watch to keep up to date with the latest upcoming changes? do it. hit that watch button. ๐Ÿ”ฅ


๐Ÿ’ฌ GETTING HELP / CONTRIBUTING ๐Ÿ’ฌ

The Dancer development team can be found on #dancer on irc.perl.org: irc://irc.perl.org/dancer

If you don't have an IRC client installed/configured, there's a simple web chat client at http://www.perldancer.org/irc waiting for you. we'll be there. ๐Ÿซถ

There's also a Dancer users mailing list available. Subscribe at:

http://lists.preshweb.co.uk/mailman/listinfo/dancer-users

If you'd like to contribute to the Dancer project, please see http://www.perldancer.org/contribute for all the ways you can help! literally every single one. go be the main character of open source. ๐Ÿ’…โœจ

๐Ÿ“ฆ DEPENDENCIES ๐Ÿ“ฆ

okay so these modules are mandatory โ€” like, Dancer literally cannot run without them, no cap:

  • HTTP::Server::Simple::PSGI
  • HTTP::Tiny
  • MIME::Types
  • URI

and these ones are optional besties โ€” cute to have, not required:

  • JSON โ€” needed to use JSON serializer
  • Plack โ€” in order to use PSGI
  • Template โ€” in order to use TT for rendering views
  • XML::Simple and <XML:SAX> or <XML:Parser> โ€” for XML serialization
  • YAML โ€” needed for configuration file support

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€


๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Dancer Core Developers โ€” iconic, periodt. ๐Ÿ’…


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 came from perl v5.40.1, dated 2026-05-05, for Dancer(3pm). stay slay โœจ๐Ÿ’–

๐Ÿ“ฆ where this page comes from