.\" 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::Cookbook 3pm" .TH Dancer::Cookbook 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::Cookbook \- a quick\-start guide to the Dancer web framework .SH "VERSION" .IX Header "VERSION" version 1.3521 .SH "DESCRIPTION" .IX Header "DESCRIPTION" A quick-start guide with examples to get you up and running with the Dancer web framework. .SH "BEGINNER'S DANCE" .IX Header "BEGINNER'S DANCE" .SS "Your first Dancer web app" .IX Subsection "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 \*(L"Hello World\*(R" example: .PP .Vb 1 \& #!/usr/bin/perl \& \& use Dancer; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Why, hello there " . params\->{name}; \& }; \& \& dance; .Ve .PP 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 .PP .Vb 2 \& $ curl http://localhost:3000/hello/Bob \& Why, hello there Bob .Ve .PP (or the name of the machine you ran it on, if it's not your local system), and it will say hello. The \f(CW\*(C`:name\*(C'\fR part is a named parameter within the route specification whose value is made available through \f(CW\*(C`params\*(C'\fR \&\- more on that later. .PP Note that you don't need to use the \f(CW\*(C`strict\*(C'\fR and \f(CW\*(C`warnings\*(C'\fR pragma, they are already loaded by Dancer. (If you don't want the \f(CW\*(C`warnings\*(C'\fR pragma (which can lead to undesired warnings about use of undef values, for example), then set the import_warnings setting to a false value. .SS "Starting a Dancer project" .IX Subsection "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 \f(CW\*(C`dancer\*(C'\fR helper script, which will build the framework of your application with a single command: .PP .Vb 10 \& $ dancer \-a mywebapp \& + mywebapp \& + mywebapp/bin \& + mywebapp/bin/app.pl \& + mywebapp/config.yml \& + mywebapp/environments \& + mywebapp/environments/development.yml \& + mywebapp/environments/production.yml \& + mywebapp/views \& + mywebapp/views/index.tt \& + mywebapp/views/layouts \& + mywebapp/views/layouts/main.tt \& + mywebapp/MANIFEST.SKIP \& + mywebapp/lib \& + mywebapp/lib/mywebapp.pm \& + mywebapp/public \& + mywebapp/public/css \& + mywebapp/public/css/style.css \& + mywebapp/public/css/error.css \& + mywebapp/public/images \& + mywebapp/public/500.html \& + mywebapp/public/404.html \& + mywebapp/public/dispatch.fcgi \& + mywebapp/public/dispatch.cgi \& + mywebapp/public/javascripts \& + mywebapp/public/javascripts/jquery.min.js \& + mywebapp/t \& + mywebapp/t/002_index_route.t \& + mywebapp/t/001_base.t \& + mywebapp/Makefile.PL .Ve .PP 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. .SH "DANCE ROUTINES: ROUTES" .IX Header "DANCE ROUTINES: ROUTES" .SS "Declaring routes" .IX Subsection "Declaring routes" To control what happens when a web request is received by your webapp, you'll need to declare \f(CW\*(C`routes\*(C'\fR. A route declaration indicates for which \s-1HTTP\s0 method(s) it is valid, the path it matches (e.g. /foo/bar), and a coderef to execute, which returns the response. .PP .Vb 3 \& get \*(Aq/hello/:name\*(Aq => sub { \& return "Hi there " . params\->{name}; \& }; .Ve .PP The above route specifies that, for \s-1GET\s0 requests to '/hello/...', the code block provided should be executed. .SS "Handling multiple \s-1HTTP\s0 request methods" .IX Subsection "Handling multiple HTTP request methods" Routes can use \f(CW\*(C`any\*(C'\fR to match all, or a specified list of \s-1HTTP\s0 methods. .PP The following will match any \s-1HTTP\s0 request to the path /myaction: .PP .Vb 3 \& any \*(Aq/myaction\*(Aq => sub { \& # code \& } .Ve .PP The following will match \s-1GET\s0 or \s-1POST\s0 requests to /myaction: .PP .Vb 3 \& any [\*(Aqget\*(Aq, \*(Aqpost\*(Aq] => \*(Aq/myaction\*(Aq => sub { \& # code \& }; .Ve .PP For convenience, any route which matches \s-1GET\s0 requests will also match \s-1HEAD\s0 requests. .SS "Retrieving request parameters" .IX Subsection "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 \s-1HTTP POST\s0 requests, the content of the \&\s-1POST\s0 body. .SS "Named parameters in route path declarations" .IX Subsection "Named parameters in route path declarations" As seen above, you can use \f(CW\*(C`:somename\*(C'\fR in a route's path to capture part of the path; this will become available by calling params. .PP So, for a web app where you want to display information on a company, you might use something like: .PP .Vb 4 \& get \*(Aq/company/view/:companyid\*(Aq => sub { \& my $company_id = params\->{companyid}; \& # Look up the company and return appropriate page \& }; .Ve .SS "Wildcard path matching and splat" .IX Subsection "Wildcard path matching and splat" You can also declare wildcards in a path, and retrieve the values they matched with the splat keyword: .PP .Vb 11 \& get \*(Aq/*/*\*(Aq => sub { \& my ($action, $id) = splat; \& if (my $action eq \*(Aqview\*(Aq) { \& return display_item($id); \& } elsif ($action eq \*(Aqdelete\*(Aq) { \& return delete_item($id); \& } else { \& status \*(Aqnot_found\*(Aq; \& return "What?"; \& } \& }; .Ve .SS "Before hooks \- processed before a request" .IX Subsection "Before hooks - processed before a request" A before hook declares code which should be handled before a request is passed to the appropriate route. .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 The above declares a before hook which uses \f(CW\*(C`var\*(C'\fR to set a variable which will later be available within the route handler, then amends the path of the request to \f(CW\*(C`/foo/oversee\*(C'\fR; this means that, whatever path was requested, it will be treated as though the path requested was \f(CW\*(C`/foo/oversee\*(C'\fR. .SS "Default route" .IX Subsection "Default route" In case you want to avoid a \fI404 error\fR, 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. .PP The default route handler will handle any request that doesn't get served by any other route. .PP All you need to do is set up the following route as the \fBlast\fR route: .PP .Vb 4 \& any qr{.*} => sub { \& status \*(Aqnot_found\*(Aq; \& template \*(Aqspecial_404\*(Aq, { path => request\->path }; \& }; .Ve .PP Then you can set up the template as such: .PP .Vb 1 \& You tried to reach <% path %>, but it is unavailable at the moment. \& \& Please try again or contact us at our email at <...>. .Ve .SS "Using the auto_page feature for automatic route creation" .IX Subsection "Using the auto_page feature for automatic route creation" For simple \*(L"static\*(R" pages, you can simply enable the \f(CW\*(C`auto_page\*(C'\fR config setting; this means that you need not declare a route handler for those pages; if a request is for \f(CW\*(C`/foo/bar\*(C'\fR, Dancer will check for a matching view (e.g. \&\f(CW\*(C`/foo/bar.tt\*(C'\fR and render it with the default layout etc if found. For full details, see the documentation for the auto_page setting. .SS "Why should I use the Ajax plugin" .IX Subsection "Why should I use the Ajax plugin" As an Ajax query is just an \s-1HTTP\s0 query, it's similar to a \s-1GET\s0 or \s-1POST\s0 route. You may ask yourself why you may want to use the \f(CW\*(C`ajax\*(C'\fR keyword (from the Dancer::Plugin::Ajax plugin) instead of a simple \&\f(CW\*(C`get\*(C'\fR. .PP 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 \s-1HTML\s0 content. But you may also want to be able to call this same url from a javascript query using Ajax. .PP So, instead of having the following code: .PP .Vb 10 \& get \*(Aq/user/:user\*(Aq => sub { \& if (request\->is_ajax) { \& # create xml, set headers to text/xml, blablabla \& header(\*(AqContent\-Type\*(Aq => \*(Aqtext/xml\*(Aq); \& header(\*(AqCache\-Control\*(Aq => \*(Aqno\-store, no\-cache, must\-revalidate\*(Aq); \& to_xml({...}) \& }else{ \& template users, {....} \& } \& }; .Ve .PP you can have .PP .Vb 3 \& get \*(Aq/user/:user\*(Aq => sub { \& template users, {...} \& } .Ve .PP and .PP .Vb 3 \& ajax \*(Aq/user/:user\*(Aq => sub { \& to_xml({...}, RootName => undef); \& } .Ve .PP Because it's an Ajax query you know you need to return \s-1XML\s0 content, so the content type of the response is set for you. .SS "Using the prefix feature to split your application" .IX Subsection "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: .PP .Vb 3 \& package myapp; \& use Dancer \*(Aq:syntax\*(Aq; \& use myapp::admin; \& \& prefix undef; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; \& \& package myapp::admin; \& use Dancer \*(Aq:syntax\*(Aq; \& \& prefix \*(Aq/admin\*(Aq; \& \& get \*(Aq/\*(Aq => sub {...}; \& \& 1; .Ve .PP The following routes will be generated for us: .PP .Vb 4 \& \- get / \& \- get /admin/ \& \- head / \& \- head /admin/ .Ve .SH "MUSCLE MEMORY: STORING DATA" .IX Header "MUSCLE MEMORY: STORING DATA" .SS "Handling sessions" .IX Subsection "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. .PP 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: .PP .Vb 1 \& session: Simple .Ve .PP 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. .PP You can also use the Dancer::Session::YAML backend included with Dancer, which stores session data on disc in \s-1YAML\s0 files (since \s-1YAML\s0 is a nice human-readable format, it makes inspecting the contents of sessions a breeze): .PP .Vb 1 \& session: YAML .Ve .PP Or, to enable session support from within your code, .PP .Vb 1 \& set session => \*(AqYAML\*(Aq; .Ve .PP (Controlling settings is best done from your config file, though). '\s-1YAML\s0' 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 \s-1YAML\s0 backend is a simple and easy to use example which stores session data in a \s-1YAML\s0 file in sessions). .PP You can then use the session keyword to manipulate the session: .PP \fIStoring data in the session\fR .IX Subsection "Storing data in the session" .PP Storing data in the session is as easy as: .PP .Vb 1 \& session varname => \*(Aqvalue\*(Aq; .Ve .PP \fIRetrieving data from the session\fR .IX Subsection "Retrieving data from the session" .PP Retrieving data from the session is as easy as: .PP .Vb 1 \& session(\*(Aqvarname\*(Aq) .Ve .PP Or, alternatively, .PP .Vb 1 \& session\->{varname} .Ve .PP \fIControlling where sessions are stored\fR .IX Subsection "Controlling where sessions are stored" .PP 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 \f(CW\*(C`session_dir\*(C'\fR setting, which defaults to \f(CW\*(C`appdir/sessions\*(C'\fR. .PP If you need to control where session files are created, you can do so quickly and easily within your config file. For example: .PP .Vb 1 \& session_dir: /tmp/dancer\-sessions .Ve .PP If the directory you specify does not exist, Dancer will attempt to create it for you. .PP \fIDestroying a session\fR .IX Subsection "Destroying a session" .PP When you're done with your session, you can destroy it: .PP .Vb 1 \& session\->destroy .Ve .SS "Sessions and logging in" .IX Subsection "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. .PP This can easily be handled with a before hook to check their session: .PP .Vb 6 \& hook \*(Aqbefore\*(Aq => sub { \& if (! session(\*(Aquser\*(Aq) && request\->path_info !~ m{^/login}) { \& var requested_path => request\->path_info; \& request\->path_info(\*(Aq/login\*(Aq); \& } \& }; \& \& get \*(Aq/login\*(Aq => 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 \& template \*(Aqlogin\*(Aq, { path => vars\->{requested_path} }; \& }; \& \& post \*(Aq/login\*(Aq => sub { \& # Validate the username and password they supplied \& if (params\->{user} eq \*(Aqbob\*(Aq && params\->{pass} eq \*(Aqletmein\*(Aq) { \& session user => params\->{user}; \& redirect params\->{path} || \*(Aq/\*(Aq; \& } else { \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& }; .Ve .PP 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 \s-1POST\s0 submission, and can be used by the post route to redirect onwards to the page originally requested once you're logged in. .PP 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 \s-1PAM\s0 etc. Authen::Simple is probably a good starting point here! .PP A simple working example of handling authentication against a database table yourself (using Dancer::Plugin::Database which provides the \f(CW\*(C`database\*(C'\fR keyword, and Crypt::SaltedHash to handle salted hashed passwords (well, you wouldn't store your users' passwords in the clear, would you?)) follows: .PP .Vb 10 \& post \*(Aq/login\*(Aq => sub { \& my $user = database\->quick_select(\*(Aqusers\*(Aq, \& { username => params\->{user} } \& ); \& if (!$user) { \& warning "Failed login for unrecognised user " . params\->{user}; \& redirect \*(Aq/login?failed=1\*(Aq; \& } else { \& if (Crypt::SaltedHash\->validate($user\->{password}, params\->{pass})) \& { \& debug "Password correct"; \& # Logged in successfully \& session user => $user; \& redirect params\->{path} || \*(Aq/\*(Aq; \& } else { \& debug("Login failed \- password incorrect for " . params\->{user}); \& redirect \*(Aq/login?failed=1\*(Aq; \& } \& } \& }; .Ve .PP \fIRetrieve complete hash stored in session\fR .IX Subsection "Retrieve complete hash stored in session" .PP Get complete hash stored in session: .PP .Vb 1 \& my $hash = session; .Ve .SH "APPEARANCE" .IX Header "APPEARANCE" .SS "Using templates \- views and layouts" .IX Subsection "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. .PP Your route handlers can use the template keyword to render templates. .PP \fIViews\fR .IX Subsection "Views" .PP 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'. .PP 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. .PP Note that, by default, Dancer configures the Template::Toolkit engine to use \&\f(CW\*(C`<% %\*(C'\fR> brackets instead of its default \f(CW\*(C`[% %]\*(C'\fR brackets. You can change this by using the following in your config file: .PP .Vb 1 \& template: template_toolkit \& \& engines: \& template_toolkit: \& start_tag: \*(Aq[%\*(Aq \& stop_tag: \*(Aq%]\*(Aq .Ve .PP All views must have a '.tt' extension. This may change in the future. .PP To render a view just call the \f(CW\*(C`template|Dancer/template\*(C'\fR 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 for convenience, the request, session, params and vars are automatically accessible in the view, named \f(CW\*(C`request\*(C'\fR, \f(CW\*(C`session\*(C'\fR, \&\f(CW\*(C`params\*(C'\fR and \f(CW\*(C`vars\*(C'\fR). For example: .PP .Vb 1 \& hook \*(Aqbefore\*(Aq => sub { var time => scalar(localtime) }; \& \& get \*(Aq/hello/:name\*(Aq => sub { \& my $name = params\->{name}; \& template \*(Aqhello.tt\*(Aq, { name => $name }; \& }; .Ve .PP The template 'hello.tt' could contain, for example: .PP .Vb 6 \&
Hi there, <% name %>!
\&You\*(Aqre using <% request.user_agent %>
\& <% IF session.username %> \&You\*(Aqre logged in as <% session.username %> \& <% END %> \& It\*(Aqs currently <% vars.time %> .Ve .PP For a full list of the tokens automatically added to your template (like \f(CW\*(C`session\*(C'\fR, \f(CW\*(C`request\*(C'\fR and \f(CW\*(C`vars\*(C'\fR, refer to Dancer::Template::Abstract). .PP \fILayouts\fR .IX Subsection "Layouts" .PP 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 \s-1HTML :\s0) .PP Here is an example of a layout: \f(CW\*(C`views/layouts/main.tt\*(C'\fR : .PP .Vb 6 \& \&
... \& \&