1Dancer2::Manual::KeyworUdsse(r3)Contributed Perl DocumenDtaantcieorn2::Manual::Keywords(3)
2
3
4

NAME

6       Dancer2::Manual::Keywords - Dancer2 DSL Keywords
7

VERSION

9       version 0.400001
10

DSL KEYWORDS

12       Dancer2 provides you with a DSL (Domain-Specific Language) which makes
13       implementing your web application trivial.
14
15       For example, take the following example:
16
17           use Dancer2;
18
19           get '/hello/:name' => sub {
20               my $name = route_parameters->get('name');
21           };
22           true;
23
24       "get" and "route_parameters" are keywords provided by Dancer2.
25
26       This document lists all keywords provided by Dancer2. It does not cover
27       additional keywords which may be provided by loaded plugins; see the
28       documentation for plugins you use to see which additional keywords they
29       make available to you.
30
31   any
32       Defines a route for multiple HTTP methods at once:
33
34           any ['get', 'post'] => '/myaction' => sub {
35               # code
36           };
37
38       Or even, a route handler that would match any HTTP methods:
39
40           any '/myaction' => sub {
41               # code
42           };
43
44   app
45       Returns an instance of the app. App is a Dancer2::Core::App.
46
47   body_parameters
48       Returns a Hash::MultiValue object from the body parameters.
49
50           post '/' => sub {
51               my $last_name = body_parameters->get('name');
52               my @all_names = body_parameters->get_all('name');
53           };
54
55   captures
56       Returns a reference to a copy of "%+", if there are named captures in
57       the route's regular expression.
58
59           get qr{
60               / (?<object> user   | ticket | comment )
61               / (?<action> delete | find )
62               / (?<id> \d+ )
63               /?$
64           }x
65           , sub {
66               my $value_for = captures;
67               "i don't want to $value_for->{action} " .
68                   "the $value_for->{object} $value_for->{id} !"
69           };
70
71   cookie
72       Accesses a cookie value (or sets it). Note that this method will
73       eventually be preferred over "set_cookie".
74
75           cookie lang => "fr-FR";              # set a cookie and return its value
76           cookie lang => "fr-FR", expires => "2 hours";   # extra cookie info
77           cookie "lang"                        # return a cookie value
78
79       If your cookie value is a key/value URI string, like
80
81           token=ABC&user=foo
82
83       "cookie" will only return the first part ("token=ABC") if called in
84       scalar context. Use list context to fetch them all:
85
86           my @values = cookie "name";
87
88   cookies
89       Accesses cookies values, it returns a hashref of Dancer2::Core::Cookie
90       objects:
91
92           get '/some_action' => sub {
93               my $cookie = cookies->{name};
94               return $cookie->value;
95           };
96
97       In case you have stored something other than a scalar in your cookie:
98
99           get '/some_action' => sub {
100               my $cookie = cookies->{oauth};
101               my %values = $cookie->value;
102               return ($values{token}, $values{token_secret});
103           };
104
105   config
106       Accesses the configuration of the application:
107
108           get '/appname' => sub {
109               return "This is " . config->{appname};
110           };
111
112   content
113       Sets the content for the response. This only works within a delayed
114       response.
115
116       This will crash:
117
118           get '/' => sub {
119               # THIS WILL CRASH
120               content 'Hello, world!';
121           };
122
123       But this will work just fine:
124
125           get '/' => sub {
126               delayed {
127                   content 'Hello, world!';
128                   ...
129               };
130           };
131
132   content_type
133       Sets the content-type rendered, for the current route handler:
134
135           get '/cat/:txtfile' => sub {
136               content_type 'text/plain';
137
138               # here we can dump the contents of route_parameters->get('txtfile')
139           };
140
141       You can use abbreviations for content types. For instance:
142
143           get '/svg/:id' => sub {
144               content_type 'svg';
145
146               # here we can dump the image with id route_parameters->get('id')
147           };
148
149       Note that if you want to change the default content-type for every
150       route, it is easier to change the "content_type" setting instead.
151
152   context
153       Deprecated. Use "app" instead.
154
155   dance
156       Alias for the "start" keyword. "to_app" is preferable.
157
158   dancer_app
159       Returns the app object. See "app".
160
161   dancer_version
162       Returns the version of Dancer. If you need the major version, do
163       something like:
164
165           int(dancer_version);
166
167       or (better), call "dancer_major_version".
168
169   dancer_major_version
170       Returns the major version of Dancer.
171
172   debug
173       Logs a message of debug level:
174
175           debug "This is a debug message";
176
177       See Dancer2::Core::Role::Logger for details on how to configure where
178       log messages go.
179
180   decode_json ($string)
181       Deserializes a JSON structure from an UTF-8 binary string.
182
183   del
184       Defines a route for HTTP DELETE requests to the given URL:
185
186           del '/resource' => sub { ... };
187
188   delayed
189       Stream a response asynchronously. For more information, please see
190       "Delayed responses (Async/Streaming)" in Dancer2::Manual, or this
191       article <https://advent.perldancer.org/2020/22> in the 2020 Dancer
192       Advent Calendar.
193
194   dirname
195       Returns the dirname of the path given:
196
197           my $dir = dirname($some_path);
198
199   done
200       Close the streaming connection. Can only be called within a streaming
201       response callback.
202
203   dsl
204       Allows access to the DSL within your plugin/application. Is an instance
205       of Dancer2::Core::DSL.
206
207   encode_json ($structure)
208       Serializes a structure to a UTF-8 binary JSON string.
209
210       Calling this function will not trigger the serialization's hooks.
211
212   engine
213       Given a namespace, returns the current engine object
214
215           my $template_engine = engine 'template';
216           my $html = $template_engine->apply_renderer(...);
217           $template_engine->apply_layout($html);
218
219   error
220       Logs a message of error level:
221
222           error "This is an error message";
223
224       See Dancer2::Core::Role::Logger for details on how to configure where
225       log messages go.
226
227   false
228       Constant that returns a false value (0).
229
230   flush
231       Flush headers when streaming a response. Necessary when "content" is
232       called multiple times.
233
234   forward
235       Runs an "internal redirect" of the current route to another route. More
236       formally; when "forward" is executed, the current dispatch of the route
237       is aborted, the request is modified (altering query params or request
238       method), and the modified request following a new route is dispatched
239       again. Any remaining code (route and hooks) from the current dispatch
240       will never be run and the modified route's dispatch will execute hooks
241       for the new route normally.
242
243       It effectively lets you chain routes together in a clean manner.
244
245           get '/demo/articles/:article_id' => sub {
246
247               # you'll have to implement this next sub yourself :)
248               change_the_main_database_to_demo();
249
250               forward "/articles/" . route_parameters->get('article_id');
251           };
252
253       In the above example, the users that reach /demo/articles/30 will
254       actually reach /articles/30 but we've changed the database to demo
255       before.
256
257       This is pretty cool because it lets us retain our paths and offer a
258       demo database by merely going to /demo/....
259
260       You'll notice that in the example we didn't indicate whether it was GET
261       or POST. That is because "forward" chains the same type of route the
262       user reached. If it was a GET, it will remain a GET (but if you do need
263       to change the method, you can do so; read on below for details.)
264
265       Also notice that "forward" only redirects to a new route. It does not
266       redirect the requests involving static files. This is because static
267       files are handled before Dancer2 tries to match the request to a route
268       - static files take higher precedence.
269
270       This means that you will not be able to "forward" to a static file. If
271       you wish to do so, you have two options: either redirect (asking the
272       browser to make another request, but to a file path instead) or use
273       "send_file" to provide a file.
274
275       WARNING: Any code after a "forward" is ignored, until the end of the
276       route. It's not necessary to use "return" with "forward" anymore.
277
278           get '/foo/:article_id' => sub {
279               if ($condition) {
280                   forward "/articles/" . route_parameters->get('article_id');
281                   # The following code WILL NOT BE executed
282                   do_stuff();
283               }
284
285               more_stuff();
286           };
287
288       Note that "forward" doesn't parse GET arguments. So, you can't use
289       something like:
290
291           forward '/home?authorized=1';
292
293       But "forward" supports an optional hashref with parameters to be added
294       to the actual parameters:
295
296           forward '/home', { authorized => 1 };
297
298       Finally, you can add some more options to the "forward" method, in a
299       third argument, also as a hashref. That option is currently only used
300       to change the method of your request. Use with caution.
301
302           forward '/home', { auth => 1 }, { method => 'POST' };
303
304   from_dumper ($structure)
305       Deserializes a Data::Dumper structure.
306
307   from_json ($string, \%options)
308       Deserializes a JSON structure from a string. You should probably use
309       "decode_json" which expects a UTF-8 encoded binary string and handles
310       decoding it for you.
311
312   from_yaml ($structure)
313       Deserializes a YAML structure.
314
315   get
316       Defines a route for HTTP GET requests to the given path:
317
318           get '/' => sub {
319               return "Hello world";
320           }
321
322       Note that a route to match HEAD requests is automatically created as
323       well.
324
325   halt
326       Sets a response object with the content given.
327
328       When used as a return value from a hook, this breaks the execution flow
329       and renders the response immediately:
330
331           hook before => sub {
332               if ($some_condition) {
333                   halt("Unauthorized");
334
335                   # this code is not executed
336                   do_stuff();
337               }
338           };
339
340           get '/' => sub {
341               "hello there";
342           };
343
344       WARNING: Issuing a halt immediately exits the current route, and
345       performs the halt. Thus, any code after a halt is ignored, until the
346       end of the route.  Hence, it's not necessary anymore to use "return"
347       with halt.
348
349   header
350       Deprecated. Use "response_header" instead.
351
352   headers
353       Deprecated. Use "response_headers" instead.
354
355   hook
356       Adds a hook at some position. For example :
357
358         hook before_serializer => sub {
359           my $content = shift;
360           ...
361         };
362
363       There can be multiple hooks assigned to a given position, and each will
364       be executed in order.
365
366       See "HOOKS" in Dancer2::Manual for a list of available hooks.
367
368   info
369       Logs a message of "info" level:
370
371           info "This is an info message";
372
373       See Dancer2::Core::Role::Logger for details on how to configure where
374       log messages go.
375
376   log
377       Logs messages at the specified level. For example:
378
379           log( debug => "This is a debug message." );
380
381   mime
382       Shortcut to access the instance object of Dancer2::Core::MIME. You
383       should read the Dancer2::Core::MIME documentation for full details, but
384       the most commonly-used methods are summarized below:
385
386           # set a new mime type
387           mime->add_type( foo => 'text/foo' );
388
389           # set a mime type alias
390           mime->add_alias( f => 'foo' );
391
392           # get mime type for an alias
393           my $m = mime->for_name( 'f' );
394
395           # get mime type for a file (based on extension)
396           my $m = mime->for_file( "foo.bar" );
397
398           # get current defined default mime type
399           my $d = mime->default;
400
401           # set the default mime type using config.yml
402           # or using the set keyword
403           set default_mime_type => 'text/plain';
404
405   options
406       Defines a route for HTTP OPTIONS requests to the given URL:
407
408           options '/resource' => sub { ... };
409
410   param
411       This method should be called from a route handler.  This method is an
412       accessor to the parameters hash table.
413
414          post '/login' => sub {
415              my $username = param "user";
416              my $password = param "pass";
417              # ...
418          };
419
420       We now recommend using one of the specific keywords for parameters
421       ("route_parameters", "query_parameters", and "body_parameters") instead
422       of "params" or "param".
423
424   params
425       This method should be called from a route handler.  It's an alias for
426       the Dancer2::Core::Request params accessor. It returns a hash (in list
427       context) or a hash reference (in scalar context) to all defined
428       parameters. Check "param" below to access quickly to a single parameter
429       value.
430
431           post '/login' => sub {
432               # get all parameters as a single hash
433               my %all_parameters = params;
434
435               // request all parmameters from a specific source: body, query, route
436               my %body_parameters  = params('body');
437               my %route_parameters = params('route');
438               my %query_parameters = params('query');
439
440               # any $source that is not body, query, or route generates an exception
441               params('fake_source'); // Unknown source params "fake_source"
442           };
443
444       We now recommend using one of the specific keywords for parameters
445       ("route_parameters", "query_parameters", and "body_parameters") instead
446       of "params" or "param".
447
448   pass
449       This method should be called from a route handler.  Tells Dancer2 to
450       pass the processing of the request to the next matching route.
451
452       WARNING: Issuing a pass immediately exits the current route, and
453       performs the pass. Thus, any code after a pass is ignored, until the
454       end of the route. Hence, it's not necessary anymore to use "return"
455       with pass.
456
457           get '/some/route' => sub {
458               if (...) {
459                   # we want to let the next matching route handler process this one
460                   pass(...);
461
462                   # this code will be ignored
463                   do_stuff();
464               }
465           };
466
467       WARNING: You cannot set the content before passing and have it remain,
468       even if you use the "content" keyword or set it directly in the
469       response object.
470
471   patch
472       Defines a route for HTTP PATCH requests to the given URL:
473
474           patch '/resource' => sub { ... };
475
476       ("PATCH" is a relatively new and not-yet-common HTTP verb, which is
477       intended to work as a "partial-PUT", transferring just the changes;
478       please see RFC5789 <http://tools.ietf.org/html/rfc5789> for further
479       details.)
480
481   path
482       Concatenates multiple paths together, without worrying about the
483       underlying operating system:
484
485           my $path = path(dirname($0), 'lib', 'File.pm');
486
487       It also normalizes (cleans) the path aesthetically. It does not verify
488       whether the path exists, though.
489
490   post
491       Defines a route for HTTP POST requests to the given URL:
492
493           post '/' => sub {
494               return "Hello world";
495           }
496
497   prefix
498       Defines a prefix for each route handler, like this:
499
500           prefix '/home';
501
502       From here, any route handler is defined to /home/*:
503
504           get '/page1' => sub {}; # will match '/home/page1'
505
506       You can unset the prefix value:
507
508           prefix undef;
509           get '/page1' => sub {}; # will match /page1
510
511       For a safer alternative you can use lexical prefix like this:
512
513           prefix '/home' => sub {
514               ## Prefix is set to '/home' here
515
516               get ...;
517               get ...;
518           };
519           ## prefix reset to the previous version here
520
521       This makes it possible to nest prefixes:
522
523          prefix '/home' => sub {
524              ## some routes
525
526             prefix '/private' => sub {
527                ## here we are under /home/private...
528
529                ## some more routes
530             };
531             ## back to /home
532          };
533          ## back to the root
534
535       Notice: Once you have a prefix set, do not add a caret to the regex:
536
537           prefix '/foo';
538           get qr{^/bar} => sub { ... } # BAD BAD BAD
539           get qr{/bar}  => sub { ... } # Good!
540
541   prepare_app
542       You can introduce code you want to run when your app is loaded, similar
543       to the "prepare_app" in Plack::Middleware.
544
545           prepare_app {
546               my $app = shift;
547
548               ... # do your thing
549           };
550
551       You should not close over the App instance, since you receive it as a
552       first argument. If you close over it, you will have a memory leak.
553
554           my $app = app();
555
556           prepare_app {
557               do_something_with_app($app); # MEMORY LEAK
558           };
559
560   psgi_app
561       Provides the same functionality as "to_app" but uses the deprecated
562       Dispatcher engine. You should use "to_app" instead.
563
564   push_header
565       Deprecated. Use "push_response_header" instead.
566
567   push_response_header
568       Do the same as "response_header", but allow for multiple headers with
569       the same name.
570
571           get '/send/header', sub {
572               push_response_header 'x-my-header' => '1';
573               push_response_header 'x-my-header' => '2';
574               # will result in two headers "x-my-header" in the response
575           }
576
577   put
578       Defines a route for HTTP PUT requests to the given URL:
579
580           put '/resource' => sub { ... };
581
582   query_parameters
583       Returns a Hash::MultiValue object from the request parameters.
584
585           /?foo=hello
586           get '/' => sub {
587               my $name = query_parameters->get('foo');
588           };
589
590           /?name=Alice&name=Bob
591           get '/' => sub {
592               my @names = query_parameters->get_all('name');
593           };
594
595   redirect
596       Generates a HTTP redirect (302). You can either redirect to a complete
597       different site or within the application:
598
599           get '/twitter', sub {
600               redirect 'http://twitter.com/me';
601               # Any code after the redirect will not be executed.
602           };
603
604       WARNING: Issuing a "redirect" immediately exits the current route.
605       Thus, any code after a "redirect" is ignored, until the end of the
606       route.  Hence, it's not necessary anymore to use "return" with
607       "redirect".
608
609       You can also force Dancer to return a specific 300-ish HTTP response
610       code:
611
612           get '/old/:resource', sub {
613               redirect '/new/' . route_parameters->get('resource'), 301;
614           };
615
616   request
617       Returns a Dancer2::Core::Request object representing the current
618       request.
619
620       See the Dancer2::Core::Request documentation for the methods you can
621       call, for example:
622
623           request->referer;         # value of the HTTP referer header
624           request->remote_address;  # user's IP address
625           request->user_agent;      # User-Agent header value
626
627   request_data
628       Returns the request's body in data form (in case a serializer is set,
629       it will be in deserialized).
630
631       This allows us to distinguish between "body_parameters", a
632       representation of request parameters (Hash::MultiValue) and other forms
633       of content.
634
635   request_header
636       Returns request header(s).
637
638           get '/get/headers' => sub {
639               my $xfoo = request_header 'X-Foo';
640               ...
641           };
642
643   response
644       Returns the current response object, which is of type
645       Dancer2::Core::Route::REQUEST.
646
647   response_header
648       Adds a custom header to response:
649
650           get '/send/header', sub {
651               response_header 'x-my-header' => 'shazam!';
652           }
653
654       Note that it will overwrite the old value of the header, if any. To
655       avoid that, see "push_response_header".
656
657   response_headers
658       Adds custom headers to response:
659
660           get '/send/headers', sub {
661               response_headers 'X-Foo' => 'bar', 'X-Bar' => 'foo';
662           }
663
664   route_parameters
665       Returns a Hash::MultiValue object from the route parameters.
666
667           # /hello
668           get '/:foo' => sub {
669               my $foo = route_parameters->get('foo');
670           };
671
672   runner
673       Returns the runner singleton. Type is Dancer2::Core::Runner.
674
675   send_as
676       Allows the current route handler to return specific content types to
677       the client using either a specified serializer or as html.
678
679       Any Dancer2 serializer may be used. The specified serializer class will
680       be loaded if required, or an error generated if the class can not be
681       found.  Serializer configuration may be added to your apps "engines"
682       configuration.
683
684       If "html" is specified, the content will be returned assuming it is
685       HTML with appropriate "Content-Type" headers and encoded using the apps
686       configured "charset" (or UTF-8).
687
688           set serializer => 'YAML';
689           set template   => 'TemplateToolkit';
690
691           # returns html (not YAML)
692           get '/' => sub { send_as html => template 'welcome.tt' };
693
694           # return json (not YAML)
695           get '/json' => sub {
696               send_as JSON => [ some => { data => 'structure' } ];
697           };
698
699       "send_as" uses "send_file" to return the content immediately. You may
700       pass any option "send_file" supports as an extra option. For example:
701
702           # return json with a custom content_type header
703           get '/json' => sub {
704               send_as JSON => [ some => { data => 'structure' } ],
705                       { content_type => 'application/json; charset=UTF-8' },
706           };
707
708       WARNING: Issuing a send_as immediately exits the current route, and
709       performs the "send_as". Thus, any code after a "send_as" is ignored,
710       until the end of the route. Hence, it's not necessary to use "return"
711       with "send_as".
712
713           get '/some/route' => sub {
714               if (...) {
715                   send_as JSON => $some_data;
716
717                   # this code will be ignored
718                   do_stuff();
719               }
720           };
721
722   send_error
723       Returns a HTTP error. By default the HTTP code returned is 500:
724
725           get '/photo/:id' => sub {
726               if (...) {
727                   send_error("Not allowed", 403);
728               } else {
729                  # return content
730               }
731           }
732
733       WARNING: Issuing a send_error immediately exits the current route, and
734       performs the "send_error". Thus, any code after a "send_error" is
735       ignored, until the end of the route. Hence, it's not necessary anymore
736       to use "return" with "send_error".
737
738           get '/some/route' => sub {
739               if (...) {
740                   # Something bad happened, stop immediately!
741                   send_error(..);
742
743                   # this code will be ignored
744                   do_stuff();
745               }
746           };
747
748   send_file
749       Lets the current route handler send a file to the client. Note that the
750       path of the file must be relative to the public directory unless you
751       use the "system_path" option (see below).
752
753           get '/download/:file' => sub {
754               return send_file(route_parameters->get('file'));
755           }
756
757       WARNING: Issuing a "send_file" immediately exits the current route, and
758       performs the "send_file". Thus, any code after a "send_file" is
759       ignored, until the end of the route. Hence, it's not necessary anymore
760       to use "return" with "send_file".
761
762           get '/some/route' => sub {
763               if (...) {
764                   # OK, send her what she wants...
765                   send_file(...);
766
767                   # this code will be ignored
768                   do_stuff();
769               }
770           };
771
772       "send_file" will use PSGI streaming if the server supports it (most, if
773       not all, do). You can explicitly disable streaming by passing
774       "streaming => 0" as an option to "send_file".
775
776           get '/download/:file' => sub {
777               send_file( route_parameters->get('file'), streaming => 0 );
778           }
779
780       The content-type will be set depending on the current MIME types
781       definition (see "mime" if you want to define your own).
782
783       If your filename does not have an extension, you are passing in a
784       filehandle, or you need to force a specific mime type, you can pass it
785       to "send_file" as follows:
786
787           send_file(route_parameters->get('file'), content_type => 'image/png');
788           send_file($fh, content_type => 'image/png');
789
790       Also, you can use your aliases or file extension names on
791       "content_type", like this:
792
793           send_file(route_parameters->get('file'), content_type => 'png');
794
795       The encoding of the file or filehandle may be specified by passing both
796       the "content_type" and "charset" options. For example:
797
798           send_file($fh, content_type => 'text/csv', charset => 'utf-8' );
799
800       For files outside your public folder, you can use the "system_path"
801       switch. Just bear in mind that its use needs caution as it can be
802       dangerous.
803
804          send_file('/etc/passwd', system_path => 1);
805
806       If you have your data in a scalar variable, "send_file" can be useful
807       as well. Pass a reference to that scalar, and "send_file" will behave
808       as if there was a file with that contents:
809
810          send_file( \$data, content_type => 'image/png' );
811
812       Note that Dancer is unable to guess the content type from the data
813       contents.  Therefore you might need to set the "content_type" properly.
814       For this kind of usage an attribute named "filename" can be useful. It
815       is used as the Content-Disposition header, to hint the browser about
816       the filename it should use.
817
818          send_file( \$data, content_type => 'image/png'
819                             filename     => 'onion.png' );
820
821       By default the Content-Disposition header uses the "attachment" type,
822       which triggers a "Save" dialog in some browsers. Supply a
823       "content_disposition" attribute of "inline" to have the file displayed
824       inline by the browser.
825
826   session
827       Provides access to all data stored in the user's session (if any).
828
829       It can also be used as a setter to store data in the session:
830
831           # getter example
832           get '/user' => sub {
833               if (session('user')) {
834                   return "Hello, ".session('user')->name;
835               }
836           };
837
838           # setter example
839           post '/user/login' => sub {
840               ...
841               if ($logged_in) {
842                   session user => $user;
843               }
844               ...
845           };
846
847       You may also need to clear a session:
848
849           # destroy session
850           get '/logout' => sub {
851               ...
852               app->destroy_session;
853               ...
854           };
855
856       If you need to fetch the session ID being used for any reason:
857
858           my $id = session->id;
859
860   set
861       Defines a setting:
862
863           set something => 'value';
864
865       You can set more than one value at once:
866
867           set something => 'value', otherthing => 'othervalue';
868
869   setting
870       Returns the value of a given setting:
871
872           setting('something'); # 'value'
873
874   splat
875       Returns the list of captures made from a route handler with a route
876       pattern which includes wildcards:
877
878           get '/file/*.*' => sub {
879               my ($file, $extension) = splat;
880               ...
881           };
882
883       There is also the extensive splat (A.K.A. "megasplat"), which allows
884       extensive greedier matching, available using two asterisks. The
885       additional path is broken down and returned as an arrayref:
886
887           get '/entry/*/tags/**' => sub {
888               my ( $entry_id, $tags ) = splat;
889               my @tags = @{$tags};
890           };
891
892       The "splat" keyword in the above example for the route
893       /entry/1/tags/one/two would set $entry_id to 1 and $tags to "['one',
894       'two']".
895
896   start
897       Starts the application or the standalone server (depending on the
898       deployment choices).
899
900       This keyword should be called at the very end of the script, once all
901       routes are defined. At this point, Dancer2 takes over.
902
903       Prefer "to_app" instead of "start".
904
905   status
906       Changes the status code provided by an action. By default, an action
907       will produce an "HTTP 200 OK" status code, meaning everything is OK:
908
909           get '/download/:file' => {
910               if (! -f route_parameters->get('file')) {
911                   status 'not_found';
912                   return "File does not exist, unable to download";
913               }
914               # serving the file...
915           };
916
917       In that example, Dancer will notice that the status has changed, and
918       will render the response accordingly.
919
920       The "status" keyword receives either a numeric status code or its name
921       in lower case, with underscores as a separator for blanks - see the
922       list in "HTTP CODES" in Dancer2::Core::HTTP. As an example, The above
923       call translates to setting the code to 404.
924
925   template
926       Returns the response of processing the given template with the given
927       parameters (and optional settings), wrapping it in the default or
928       specified layout too, if layouts are in use.
929
930       An example of a  route handler which returns the result of using
931       template to build a response with the current template engine:
932
933           get '/' => sub {
934               ...
935               return template 'some_view', { token => 'value'};
936           };
937
938       Note that "template" simply returns the content, so when you use it in
939       a route handler, if execution of the route handler should stop at that
940       point, make sure you use "return" to ensure your route handler returns
941       the content.
942
943       Since "template" just returns the result of rendering the template, you
944       can also use it to perform other templating tasks, e.g. generating
945       emails:
946
947           post '/some/route' => sub {
948               if (...) {
949                   email {
950                       to      => 'someone@example.com',
951                       from    => 'foo@example.com',
952                       subject => 'Hello there',
953                       msg     => template('emails/foo', { name => body_parameters->get('name') }),
954                   };
955
956                   return template 'message_sent';
957               } else {
958                   return template 'error';
959               }
960           };
961
962       Compatibility notice: "template" was changed in version 1.3090 to
963       immediately interrupt execution of a route handler and return the
964       content, as it's typically used at the end of a route handler to return
965       content.  However, this caused issues for some people who were using
966       "template" to generate emails etc, rather than accessing the template
967       engine directly, so this change has been reverted in 1.3091.
968
969       The first parameter should be a template available in the views
970       directory, the second one (optional) is a hashref of tokens to
971       interpolate, and the third (again optional) is a hashref of options.
972
973       For example, to disable the layout for a specific request:
974
975           get '/' => sub {
976               template 'index', {}, { layout => undef };
977           };
978
979       Or to request a specific layout, of course:
980
981           get '/user' => sub {
982               template 'user', {}, { layout => 'user' };
983           };
984
985       Some tokens are automatically added to your template ("perl_version",
986       "dancer_version", "settings", "request", "vars" and, if you have
987       sessions enabled, "session"). Check Default Template Variables for
988       further details.
989
990   to_app
991       Returns the PSGI coderef for the current (and only the current)
992       application.
993
994       You can call it as a method on the class or as a DSL:
995
996           my $app = MyApp->to_app;
997
998           # or
999
1000           my $app = to_app;
1001
1002       There is a Dancer Advent Calendar article
1003       <http://advent.perldancer.org/2014/9> covering this keyword and its
1004       usage further.
1005
1006   to_dumper ($structure)
1007       Serializes a structure with Data::Dumper.
1008
1009       Calling this function will not trigger the serialization's hooks.
1010
1011   to_json ($structure, \%options)
1012       Serializes a structure to JSON. You should probably use "encode_json"
1013       instead which handles encoding the result for you.
1014
1015   to_yaml ($structure)
1016       Serializes a structure to YAML.
1017
1018       Calling this function will not trigger the serialization's hooks.
1019
1020   true
1021       Constant that returns a true value (1).
1022
1023   upload
1024       Provides access to file uploads. Any uploaded file is accessible as a
1025       Dancer2::Core::Request::Upload object. You can access all parsed
1026       uploads via:
1027
1028           post '/some/route' => sub {
1029               my $file = upload('file_input_foo');
1030               # $file is a Dancer2::Core::Request::Upload object
1031           };
1032
1033       If you named multiple inputs of type "file" with the same name, the
1034       "upload" keyword would return an Array of
1035       Dancer2::Core::Request::Upload objects:
1036
1037           post '/some/route' => sub {
1038               my ($file1, $file2) = upload('files_input');
1039               # $file1 and $file2 are Dancer2::Core::Request::Upload objects
1040           };
1041
1042       You can also access the raw hashref of parsed uploads via the current
1043       "request" object:
1044
1045           post '/some/route' => sub {
1046               my $all_uploads = request->uploads;
1047               # $all_uploads->{'file_input_foo'} is a Dancer2::Core::Request::Upload object
1048               # $all_uploads->{'files_input'} is an arrayref of Dancer2::Core::Request::Upload objects
1049           };
1050
1051       Note that you can also access the filename of the upload received via
1052       the "body_parameters" keyword:
1053
1054           post '/some/route' => sub {
1055               # body_parameters->get('files_input') is the filename of the file uploaded
1056           };
1057
1058       See Dancer2::Core::Request::Upload for details about the interface
1059       provided.
1060
1061   uri_for
1062       Returns a fully-qualified URI for the given path:
1063
1064           get '/' => sub {
1065               redirect uri_for('/path');
1066               # can be something like: http://localhost:5000/path
1067           };
1068
1069       Query string parameters can be provided by passing a hashref as a
1070       second param:
1071
1072           uri_for('/path', { foo => 'bar' });
1073           # would return e.g. http://localhost:5000/path?foo=bar
1074
1075       By default, the parameters will be URL encoded:
1076
1077           uri_for('/path', { foo => 'hope;faith' });
1078           # would return http://localhost:5000/path?foo=hope%3Bfaith
1079
1080       If desired (for example, if you've already encoded your query
1081       parameters and you want to prevent double encoding) you can disable URL
1082       encoding via a third parameter:
1083
1084           uri_for('/path', { foo => 'qux%3Dquo' }, 1);
1085           # would return http://localhost:5000/path?foo=qux%3Dquo
1086
1087   var
1088       Provides an accessor for variables shared between hooks and route
1089       handlers. Given a key/value pair, it sets a variable:
1090
1091           hook before => sub {
1092               var foo => 42;
1093           };
1094
1095       Later, route handlers and other hooks will be able to read that
1096       variable:
1097
1098           get '/path' => sub {
1099               my $foo = var 'foo';
1100               ...
1101           };
1102
1103   vars
1104       Returns the hashref of all shared variables set during the hook/route
1105       chain with the "var" keyword:
1106
1107           get '/path' => sub {
1108               if (vars->{foo} eq 42) {
1109                   ...
1110               }
1111           };
1112
1113   warning
1114       Logs a warning message through the current logger engine:
1115
1116           warning "This is a warning";
1117
1118       See Dancer2::Core::Role::Logger for details on how to configure where
1119       log messages go.
1120

AUTHOR

1122       Dancer Core Developers
1123
1125       This software is copyright (c) 2023 by Alexis Sukrieh.
1126
1127       This is free software; you can redistribute it and/or modify it under
1128       the same terms as the Perl 5 programming language system itself.
1129
1130
1131
1132perl v5.38.0                      2023-07-20      Dancer2::Manual::Keywords(3)
Impressum