-
Notifications
You must be signed in to change notification settings - Fork 209
Wiki Cookbook
This page is a wiki version of the dancer cookbook. It is based on Dancer::Cookbook, v1.1806_2. This version will grow according to the user input, so feel free to contribute.
The official cookbook is more concise. This wiki version can be more verbose. The idea is to explain Dancer’s basic feature by practical and comprehensible examples. Maybe we can even tweak in a little of that humor that was part of Tom Christiansen’s classic perl cookbook.
Usually you will want to install from cpan, e.g. like this or using your preferred client (cpanplus, cpanminus etc.)
- perl -MCPAN -e ‘install Dancer’
Or install Dancer from github, if you like
#git clone http://github.com/sukria/Dancer.git Dancer
#and then the usual
#cd Dancer
#perl Makefile.PL
#make
#make test
#make install
That’s really easy. Dancer does not have many dependencies. See the readme file that comes with Dancer for current info on dependencies.
Dancer has been designed to be easy to work with – it’s trivial to write a simple web app, but still has the power to work with larger projects. To start with, let’s make an incredibly simple “Hello World” example:
#!/usr/bin/perl
Yes – the above is a fully-functioning web app; running that script will launch a webserver listening on the default port (3000); you can point your browser at http://localhost:3000/hello/Bob (or the name of the machine you ran it on, if it’s not your local system), and it will say hello. The :name part is a named parameter within the route specification, whose value is made available through params – more on that later.
Note that you don’t need to use the strict and warnings pragma, they are already loaded by Dancer.
Starting a Dancer project
The first simple example is fine for trivial projects, but for anything more complex, you’ll want a more maintainable solution – enter the dancer helper script, which will build the framework of your application with a single command:
$ dancer -a mywebapp + [D] mywebapp + [F] mywebapp/config.yml + [D] mywebapp/views + [D] mywebapp/views/layouts + [F] mywebapp/views/layouts/main.tt + [F] mywebapp/views/index.tt + [D] mywebapp/environments + [F] mywebapp/environments/production.yml + [F] mywebapp/environments/development.yml + [F] mywebapp/mywebapp.pm + [F] mywebapp/mywebapp.pl + [F] mywebapp/app.psgiAs you can see, it creates a directory named after the name of the app, along with a configuration file, a views directory (where your templates and layouts will live), an environments directory (where environment-specific settings live), a module containing the actual guts of your application, a script to start it, and an app.psgi file – this will only be of interest if you’re running your web app via Plack/PSGI – more on that later.
Declaring routes
To control what happens when a web request is received by your webapp, you’ll need to declare routes. A route declaration indicates which HTTP method(s) it is valid for, the path it matches (e.g. /foo/bar), and a coderef to execute, which returns the response.
get ‘/hello/:name’ => sub { return "Hi there " . params→{name}; };The above route specifies that, for GET requests to ‘/hello/…’, the code block provided should be executed.
Handling multiple HTTP request methods
Routes can use any to match all, or a specified list of HTTP methods.
The following will match any HTTP request to the path /myaction:
any ‘/myaction’ => sub {- code
}
The following will match GET or POST requests to /myaction:
any [‘get’, ‘post’] => ‘/myaction’ => sub {- code
};
For convenience, any route which matches GET requests will also match HEAD requests.
Retrieving request parameters
The params method returns a hashref of request parameters; these will be parameters supplied on the query string, within the path itself (with named placeholders), and, for HTTTP POST requests, the content of the POST body.
Named parameters in route path declarations
As seen above, you can use :somename in a route’s path to capture part of the path; this will become available by calling params.
So, for a web app where you want to display information on a company, you might use something like:
get ‘/company/view/:companyid’ => sub { my $company_id = params→{companyid};- Look up the company and return appropriate page
};
Wildcard path matching and splat
You can also declare wildcards in a path, and retrieve the values they matched with splat:
get ‘//’ => sub { my ($action, $id) = splat; if (my $action eq ‘view’) { return display_item($id); } elsif ($action eq ‘delete’) { return delete_item($id); } else { status ‘not_found’; return “What?”; } };Before filters – processed before a request
A before filter declares code which should be handled before a request is passed to the appropriate route.
before sub { var note => ‘Hi there’; request→path(‘/foo/oversee’) }; get ‘/foo/*’ => sub { my ($match) = splat; # ‘oversee’; vars→{note}; # ‘Hi there’ };The above declares a before filter which uses var to set a variable which will later be available within the route handler, then amends the path of the request to /foo/oversee; this means that, whatever path was requested, it will be treated as though the path requested was /foo/oversee.
Default route
In case you want to avoid a 404 error, or handle multiple routes in the same way and you don’t feel like configuring all of them, you can set up a default route handler.
The default route handler will handle any request that doesn’t get served by any other route.
All you need to do is set up the following route as the last route:
any r(‘.*’) => sub { status ‘not_found’; template => ‘special_404’, { path => request→path }; };Then you can set up the template as such:
You tried to reach <% path %>, but it is unavailable at the moment. Please try again or contact us at our email at <…>.Using the auto_page feature for automatic route creation
For simple pages where you’re not doing anything dynamic, but still want to use the template engine to provide headers etc, you can use the auto_page feature to avoid the need to create a route for each page.
With auto_page enabled, if the requested path does not match any specific route, Dancer will check in the views directory for a matching template, and use it to satisfy the request if found.
Simply enable auto_page in your config:
auto_page: 1Then, if you request /foo/bar, Dancer will look in the views dir for /foo/bar.tt.
Handling sessions
It’s common to want to use sessions to give your web applications state; for instance, allowing a user to log in, creating a session, and checking that session on subsequent requests.
To make use of sessions, you must first enable the session engine – pick the session engine you want to use, then declare it in your config file: config file, add:
session: SimpleThe Dancer::Session::Simple backend implements very simple in-memory session storage. This will be fast and useful for testing, but sessions do not persist between restarts of your app.
You can also use the Dancer::Session::YAML backend included with Dancer, which stores session data on disc in YAML files (since YAML is a nice human-readable format, it makes inspecting the contents of sessions a breeze):
session: YAMLOr, to enable session support from within your code,
set session => ‘YAML’;(Controlling settings is best done from your config file, though). ‘YAML’ in the example is the session backend to use; this is shorthand for Dancer::Session::YAML. There are other session backends you may wish to use, for instance Dancer::Session::Memcache, but the YAML backend is a simple and easy to use example which stores session data in a YAML file in sessions).
Storing data in the session
Storing data in the session is as easy as:
session varname => ‘value’;Retrieving data from the session
Retrieving data from the session is as easy as:
session(‘varname’)Or, alternatively,
session→{varname}Controlling where sessions are stored
For disc-based session back ends like Dancer::Session::YAML, Dancer::Session::Storable etc, session files are written to the session dir specified by the session_dir setting, which defaults to appdir/sessions if not specifically set.
If you need to control where session files are created, you can do so quickly and easily within your config file, for example:
session_dir: /tmp/dancer-sessionsIf the directory you specify does not exist, Dancer will attempt to create it for you.
Sessions and logging in
A common requirement is to check the user is logged in, and, if not, require them to log in before continuing.
This can easily be handled with a before filter to check their session:
before sub { if (! session(‘user’) && request→path_info !~ m{^/login}) { var requested_path => request→path_info; request→path_info(‘/login’); } }; get ‘/login’ => sub {- Display a login page; the original URL they requested is available as
- vars→{requested_path}, so could be put in a hidden field in the form
};
- Validate the username and password they supplied
if (params→{user} eq ‘bob’ && params→{pass} eq ‘letmein’) {
session user => params→{user};
redirect params→{path} || ‘/’;
} else {
redirect ‘/login?failed=1’;
}
};
Using templates – views and layouts
Returning plain content is all well and good for examples or trivial apps, but soon you’ll want to use templates to maintain separation between your code and your content. Dancer makes this easy.
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.
You can change this location by changing the setting ‘views’.
By default, the internal template engine Dancer::Template::Simple is used, 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, by default, Dancer configures the Template::Toolkit engine to use <% > brackets instead of its default [ %] brackets. You can change this by using the following in your config file:
template: template_toolkit engines: template_toolkit: start_tag: ‘[%’ stop_tag: ‘%]’All views must have a ‘.tt’ extension. This may change in the future.
In order to render a view, just call the template keyword at the end of the action by giving the view name and the HASHREF of tokens to interpolate in the view (note that for convenience, the request, session and route params are automatically accessible in the view, named request, session and params) – for example:
get ‘/hello/:name’ => sub { my $name = params→{name}; template ‘hello.tt’, { name => $name }; };The template ‘hello.tt’ could contain, for example:
Hi there, <% name %>!
You’re using <% request.user_agent %>
<% IF session.username %>You’re logged in as <% session.username >
< END %>
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, and have each individual view contain only the specific content. This is a good thing to avoid lots of needless duplication of HTML :)
Here is an example of a layout: views/layouts/main.tt :
You can tell your app which layout to use with layout: name in the config file, or within your code:
layout ‘main’;Configuration and environments
Configuring a Dancer application can be done in many ways. The easiest one (and maybe the 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 define all your settings in the file `appdir/config.yml’. For this, you must have installed the YAML module, and of course, write the config file 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 commandline switch.
Typically, you’ll want to set the following values in a development config file:
- appdir/environments/development.yml
log: ‘debug’
access_log: 1
show_errors: 1
And in a production one:
- appdir/environments/production.yml
log: ‘warning’
access_log: 0
show_errors: 0
Accessing configuration information from your app
A Dancer application can use the ‘config’ keyword to easily access the settings within its config file, for instance:
get ‘/appname’ => sub { return "This is " . config→{appname}; };This makes keeping your application’s settings all in one place simple and easy – you shouldn’t need to worry about implementing all that yourself :)
Logging
Configuring logging
It’s possible to log messages generated by the application and by Dancer itself.
To start logging, select the logging engine you wish to use with the logger setting; Dancer includes built-in log engines named file and console, which log to a logfile and to the console respectively.
To enable logging to a file, add the following to your config.yml:
logger: ‘file’Then you can choose which kind of messages you want to actually log:
log: ‘core’ # will log debug, warning and errors, and messages from- Dancer itself
log: ‘debug’ # will log debug, warning and errors
log: ‘warning’ # will log warning and errors
log: ‘error’ # will log only errors
If you’re using the file logging engine, a directory appdir/logs will be created and will host one logfile per environment. The log message contains the time it was written, the PID of the current process, the message and the caller information (file and line).
Logging your own messages
Just call debug, warning or error with your message:
debug “This is a debug message from my app.”;Writing a REST application
With Dancer, it’s easy to write REST application. Dancer provides helpers to serialize and deserialize for the following data format:
JSON
YAML
XML
Data::Dumper
To activate this feature, you only have to write this:
serializer => ‘JSON’From now, all hash ref or array ref returned by a route will be serialized to JSON. And all data receive from POST or PUT will be deserialized from JSON.
get ‘/hello/:name’ => sub {- this structure will be returned to the client as
- {"name":“$name”}
return {name => params→{name}};
};
It’s possible to let the client choose which serializer he want to use. For this, use the mutable serializer, and an appropriate serializer will be choosen from the Content-Type header.
Deploying your Dancer applications
For examples on deploying your Dancer applications (including standalone, behind proxy/load-balancing software, and using common web servers including Apache to run via CGI/FastCGI etc, see Dancer::Deployment.