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