NAME

VERSION

version 1.3134

DESCRIPTION

A quick-start guide with examples to get you up and running with the Dancer web framework.

BEGINNER'S DANCE

Your first Dancer web app

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:

Yes, the above is a fully-functioning web app; running that script will launch a webserver listening on the default port (3000). Now you can make a request

$ curl http://localhost:3000/hello/Bob
Why, hello there 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. (If you don't want the warnings pragma (which can lead to undesired warnings about use of undef values, for example), then set the import_warnings setting to a false value.

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:

As 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 - or to run your web app via Plack/PSGI - more on that later.

DANCE ROUTINES: ROUTES

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 for which HTTP method(s) it is valid, 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 keyword returns a hashref of request parameters; these will be parameters supplied on the query string, within the path itself (with named placeholders), and, for HTTP 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:

The above declares a before hook 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.

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 "static" pages, you can simply enable the auto_page config setting; this means that you need not declare a route handler for those pages; if a request is for /foo/bar, Dancer will check for a matching view (e.g. /foo/bar.tt and render it with the default layout etc if found. For full details, see the documentation for the auto_page setting.

Why should I use the Ajax plugin

As an Ajax query is just an HTTP query, it's similar to a GET or POST route. You may ask yourself why you may want to use the ajax keyword (from the Dancer::Plugin::Ajax plugin) instead of a simple get.

Let's say you have a path like '/user/:user' in your application. You may want to be able to serve this page, with a layout and HTML content. But you may also want to be able to call this same url from a javascript query using Ajax.

Because it's an Ajax query you know you need to return XML content, so the content type of the response is set for you.

Using the prefix feature to split your application

For better maintainability you may want to separate some of your application components to different packages. Let's say we have a simple web app with an admin section, and want to maintain this in a different package:

MUSCLE MEMORY: STORING DATA

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:

session: Simple

The 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: YAML

Or, 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).

In your login page template, you'll want a text field named user, a password field named pass, and a hidden field named path, which will be populated with the path originally requested, so that it's sent back in the POST submission, and can be used by the post route to redirect onwards to the page originally requested once you're logged in.

Of course you'll probably want to validate your users against a database table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via PAM etc. Authen::Simple is probably a good starting point here!

A simple working example of handling authentication against a database table yourself (using Dancer::Plugin::Database which provides the database keyword, and Crypt::SaltedHash to handle salted hashed passwords (well, you wouldn't store your users' passwords in the clear, would you?)) follows:

To render a view just call the template|Dancer/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, params and vars are automatically accessible in the view, named request, session, params and vars). For example:

For a full list of the tokens automatically added to your template (like session, request and vars, refer to Dancer::Template::Abstract).

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 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 :)

You can tell your app which layout to use with layout: name in the config file, or within your code:

set layout => 'main';

You can control which layout to use (or whether to use a layout at all) for a specific request without altering the layout setting by passing an options hashref as the third param to the template keyword:

template 'index.tt', {}, { layout => undef };

If your application is not mounted under root (/), you can use a before_template_render hook instead of hardcoding the path to your application for your css, images and javascript:

From now on, you can mount your application wherever you want, without any further modification of the css inclusion

template and unicode

If you use Plack and have some unicode problem with your Dancer application, don't forget to check if you have set your template engine to use unicode, and set the default charset to UTF-8. So, if you are using template toolkit, your config.yml will look like this:

charset: UTF-8
engines:
template_toolkit:
ENCODING: utf8

TT's WRAPPER directive in Dancer (META variables, SETs)

Dancer already provides a WRAPPER-like ability, which we call a "layout". The reason we do not use TT's WRAPPER (which also makes it incompatible with Dancer) is because not all template systems support it. Actually, most don't.

However, you might want to use it, and be able to define META variables and regular Template::Toolkit variables.

These few steps will get you there:

Disable the layout in Dancer

You can do this by simply commenting (or removing) the layout configuration in the config.yml file.

Done! Everything will work fine out of the box, including variables and META variables.

SETTING THE STAGE: CONFIGURATION AND LOGGING

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 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 one 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:

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 :)

Accessing configuration information from a separate script

You may well want to access your webapp's configuration from outside your webapp. You could, of course, use the YAML module of your choice and load your webapps's config.yml, but chances are that this is not convenient.

Use Dancer instead. Without any ado, magic or too big jumps, you can use the values from config.yml and some additional default values:

Note that config->{log} should result in an undef error on a default scaffold since you did not load the environment and in the default scaffold log is defined in the environment and not in config.yml. Hence undef.

If you want to load an environment you need to tell Dancer where to look for it. One way to do so, is to tell Dancer where the webapp lives. From there Dancer deduces where the config.yml file is (typically $webapp/config.yml).

By default Dancer loads development environment (typically $webapp/environment/development.yml). In contrast to the example before, you do have a value from the development environment (environment/development.yml) now. Also note that in the above example Cwd and FindBin are used. They are likely to be already loaded by Dancer anyways, so it's not a big overhead. You could just as well hand over a simple path for the app if you like that better, e.g.:

By the way, you not only get values, you can also set values straightforward like we do above with config->{environment}='production'. Of course, this value does not get written in any file; it only lives in memory and your webapp doesn't have access to it, but you can use it inside your script.

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.

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

RESTING

Writing a REST application

With Dancer, it's easy to write REST applications. Dancer provides helpers to serialize and deserialize for the following data formats:

JSON

YAML

XML

Data::Dumper

To activate this feature, you only have to set the serializer setting to the format you require, for instance in your config.yml:

serializer: JSON

Or right in your code:

set serializer => 'JSON';

From now, all HashRefs or ArrayRefs returned by a route will be serialized to the format you chose, and all data received from POST or PUT requests will be automatically deserialized.

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 wants to use. For this, use the mutable serializer, and an appropriate serializer will be chosen from the Content-Type header.

It's also possible to return a custom error, using the send_error keyword.. When you don't use a serializer, the send_error function will take a string as the first parameter (the message), and an optional HTTP code. When using a serializer, the message can be a string, an ArrayRef or a HashRef:

The content of the error will be serialized using the appropriate serializer.

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.

DANCER ON THE STAGE: DEPLOYMENT

Plack middlewares

If you deploy with Plack and use some Plack middlewares, you can enable them directly from Dancer's configuration files.

Generic middlewares

To enable middlewares in Dancer, you just have to set the plack_middlewares setting like the following: