1Mojolicious::Plugin::DeUfsaeurltCHoenltpreirbsu(t3e)d PeMroljoDloiccuimoeunst:a:tPiloungin::DefaultHelpers(3)
2
3
4

NAME

6       Mojolicious::Plugin::DefaultHelpers - Default helpers plugin
7

SYNOPSIS

9         # Mojolicious
10         $app->plugin('DefaultHelpers');
11
12         # Mojolicious::Lite
13         plugin 'DefaultHelpers';
14

DESCRIPTION

16       Mojolicious::Plugin::DefaultHelpers is a collection of helpers for
17       Mojolicious.
18
19       This is a core plugin, that means it is always enabled and its code a
20       good example for learning to build new plugins, you're welcome to fork
21       it.
22
23       See "PLUGINS" in Mojolicious::Plugins for a list of plugins that are
24       available by default.
25

HELPERS

27       Mojolicious::Plugin::DefaultHelpers implements the following helpers.
28
29   accepts
30         my $formats = $c->accepts;
31         my $format  = $c->accepts('html', 'json', 'txt');
32
33       Select best possible representation for resource from "format"
34       "GET"/"POST" parameter, "format" stash value or "Accept" request header
35       with "accepts" in Mojolicious::Renderer, defaults to returning the
36       first extension if no preference could be detected.
37
38         # Check if JSON is acceptable
39         $c->render(json => {hello => 'world'}) if $c->accepts('json');
40
41         # Check if JSON was specifically requested
42         $c->render(json => {hello => 'world'}) if $c->accepts('', 'json');
43
44         # Unsupported representation
45         $c->render(data => '', status => 204)
46           unless my $format = $c->accepts('html', 'json');
47
48         # Detected representations to select from
49         my @formats = @{$c->accepts};
50
51   app
52         %= app->secrets->[0]
53
54       Alias for "app" in Mojolicious::Controller.
55
56   b
57         %= b('Joel is a slug')->slugify
58
59       Turn string into a Mojo::ByteStream object.
60
61   c
62         %= c('a', 'b', 'c')->shuffle->join
63
64       Turn list into a Mojo::Collection object.
65
66   config
67         %= config 'something'
68
69       Alias for "config" in Mojolicious.
70
71   content
72         %= content foo => begin
73           test
74         % end
75         %= content bar => 'Hello World!'
76         %= content 'foo'
77         %= content 'bar'
78         %= content
79
80       Store partial rendered content in a named buffer and retrieve it later,
81       defaults to retrieving the named buffer "content", which is used by the
82       renderer for the "layout" and "extends" features. New content will be
83       ignored if the named buffer is already in use.
84
85   content_for
86         % content_for foo => begin
87           test
88         % end
89         %= content_for 'foo'
90
91       Same as "content", but appends content to named buffers if they are
92       already in use.
93
94         % content_for message => begin
95           Hello
96         % end
97         % content_for message => begin
98           world!
99         % end
100         %= content 'message'
101
102   content_with
103         % content_with foo => begin
104           test
105         % end
106         %= content_with 'foo'
107
108       Same as "content", but replaces content of named buffers if they are
109       already in use.
110
111         % content message => begin
112           world!
113         % end
114         % content_with message => begin
115           Hello <%= content 'message' %>
116         % end
117         %= content 'message'
118
119   csrf_token
120         %= csrf_token
121
122       Get CSRF token from "session", and generate one if none exists.
123
124   current_route
125         % if (current_route 'login') {
126           Welcome to Mojolicious!
127         % }
128         %= current_route
129
130       Check or get name of current route.
131
132   dumper
133         %= dumper {some => 'data'}
134
135       Dump a Perl data structure with "dumper" in Mojo::Util, very useful for
136       debugging.
137
138   exception_format
139         my $format = $c->exception_format;
140         $c         = $c->exception_format('txt');
141
142       Format for HTTP exceptions ("html", "json", or "txt"), defaults to the
143       value of "exception_format" in Mojolicious.
144
145   extends
146         % extends 'blue';
147         % extends 'blue', title => 'Blue!';
148
149       Set "extends" stash value, all additional key/value pairs get merged
150       into the "stash".
151
152   flash
153         my $foo = $c->flash('foo');
154         $c      = $c->flash({foo => 'bar'});
155         $c      = $c->flash(foo => 'bar');
156         %= flash 'foo'
157
158       Data storage persistent only for the next request, stored in the
159       "session".
160
161         # Show message after redirect
162         $c->flash(message => 'User created successfully!');
163         $c->redirect_to('show_user', id => 23);
164
165   inactivity_timeout
166         $c = $c->inactivity_timeout(3600);
167
168       Use "stream" in Mojo::IOLoop to find the current connection and
169       increase timeout if possible.
170
171         # Longer version
172         Mojo::IOLoop->stream($c->tx->connection)->timeout(3600);
173
174   include
175         %= include 'menubar'
176         %= include 'menubar', format => 'txt'
177
178       Alias for "render_to_string" in Mojolicious::Controller.
179
180   is_fresh
181         my $bool = $c->is_fresh;
182         my $bool = $c->is_fresh(etag => 'abc');
183         my $bool = $c->is_fresh(etag => 'W/"def"');
184         my $bool = $c->is_fresh(last_modified => $epoch);
185
186       Check freshness of request by comparing the "If-None-Match" and
187       "If-Modified-Since" request headers to the "ETag" and "Last-Modified"
188       response headers with "is_fresh" in Mojolicious::Static.
189
190         # Add ETag/Last-Modified headers and check freshness before rendering
191         $c->is_fresh(etag => 'abc', last_modified => 1424985708)
192           ? $c->rendered(304)
193           : $c->render(text => 'I ♥ Mojolicious!');
194
195   layout
196         % layout 'green';
197         % layout 'green', title => 'Green!';
198
199       Set "layout" stash value, all additional key/value pairs get merged
200       into the "stash".
201
202   log
203         my $log = $c->log;
204
205       Alternative to "log" in Mojolicious that includes "request_id" in
206       Mojo::Message::Request with every log message.
207
208         # Log message with context
209         $c->log->debug('This is a log message with request id');
210
211         # Pass logger with context to model
212         my $log = $c->log;
213         $c->some_model->create({foo => $foo}, $log);
214
215   param
216         %= param 'foo'
217
218       Alias for "param" in Mojolicious::Controller.
219
220   proxy->get_p
221         my $promise = $c->proxy->get_p('http://example.com' => {Accept => '*/*'});
222
223       Perform non-blocking "GET" request and forward response as efficiently
224       as possible, takes the same arguments as "get" in Mojo::UserAgent and
225       returns a Mojo::Promise object.
226
227         # Forward with exception handling
228         $c->proxy->get_p('http://mojolicious.org')->catch(sub ($err) {
229           $c->log->debug("Proxy error: $err");
230           $c->render(text => 'Something went wrong!', status => 400);
231         });
232
233   proxy->post_p
234         my $promise = $c->proxy->post_p('http://example.com' => {Accept => '*/*'});
235
236       Perform non-blocking "POST" request and forward response as efficiently
237       as possible, takes the same arguments as "post" in Mojo::UserAgent and
238       returns a Mojo::Promise object.
239
240         # Forward with exception handling
241         $c->proxy->post_p('example.com' => form => {test => 'pass'})->catch(sub ($err) {
242           $c->log->debug("Proxy error: $err");
243           $c->render(text => 'Something went wrong!', status => 400);
244         });
245
246   proxy->start_p
247         my $promise = $c->proxy->start_p(Mojo::Transaction::HTTP->new);
248
249       Perform non-blocking request for a custom Mojo::Transaction::HTTP
250       object and forward response as efficiently as possible, returns a
251       Mojo::Promise object.
252
253         # Forward with exception handling
254         my $tx = $c->ua->build_tx(GET => 'http://mojolicious.org');
255         $c->proxy->start_p($tx)->catch(sub ($err) {
256           $c->log->debug("Proxy error: $err");
257           $c->render(text => 'Something went wrong!', status => 400);
258         });
259
260         # Forward with custom request and response headers
261         my $headers = $c->req->headers->clone->dehop;
262         $headers->header('X-Proxy' => 'Mojo');
263         my $tx = $c->ua->build_tx(GET => 'http://example.com' => $headers->to_hash);
264         $c->proxy->start_p($tx);
265         $tx->res->content->once(body => sub ($content) { $c->res->headers->header('X-Proxy' => 'Mojo') });
266
267   redirect_to
268         $c = $c->redirect_to('named', foo => 'bar');
269         $c = $c->redirect_to('named', {foo => 'bar'});
270         $c = $c->redirect_to('/index.html');
271         $c = $c->redirect_to('http://example.com/index.html');
272
273       Prepare a 302 (if the status code is not already "3xx") redirect
274       response with "Location" header, takes the same arguments as "url_for".
275
276         # Moved Permanently
277         $c->res->code(301);
278         $c->redirect_to('some_route');
279
280         # Temporary Redirect
281         $c->res->code(307);
282         $c->redirect_to('some_route');
283
284   reply->asset
285         $c->reply->asset(Mojo::Asset::File->new);
286
287       Reply with a Mojo::Asset::File or Mojo::Asset::Memory object using
288       "serve_asset" in Mojolicious::Static, and perform content negotiation
289       with "Range", "If-Modified-Since" and "If-None-Match" headers.
290
291         # Serve asset with custom modification time
292         my $asset = Mojo::Asset::Memory->new;
293         $asset->add_chunk('Hello World!')->mtime(784111777);
294         $c->res->headers->content_type('text/plain');
295         $c->reply->asset($asset);
296
297         # Serve static file if it exists
298         if (my $asset = $c->app->static->file('images/logo.png')) {
299           $c->res->headers->content_type('image/png');
300           $c->reply->asset($asset);
301         }
302
303   reply->exception
304         $c = $c->reply->exception('Oops!');
305         $c = $c->reply->exception(Mojo::Exception->new);
306
307       Render an exception response in the appropriate format by delegating to
308       more specific exception helpers.
309
310   reply->file
311         $c->reply->file('/etc/passwd');
312
313       Reply with a static file from an absolute path anywhere on the file
314       system using "static" in Mojolicious.
315
316         # Longer version
317         $c->reply->asset(Mojo::Asset::File->new(path => '/etc/passwd'));
318
319         # Serve file from an absolute path with a custom content type
320         $c->res->headers->content_type('application/myapp');
321         $c->reply->file('/home/sri/foo.txt');
322
323         # Serve file from a secret application directory
324         $c->reply->file($c->app->home->child('secret', 'file.txt'));
325
326   reply->html_exception
327         $c = $c->reply->html_exception('Oops!');
328         $c = $c->reply->html_exception(Mojo::Exception->new);
329
330       Render the exception template "exception.$mode.$format.*" or
331       "exception.$format.*" and set the response status code to 500. Also
332       sets the stash values "exception" to a Mojo::Exception object and
333       "snapshot" to a copy of the "stash" for use in the templates.
334
335   reply->html_not_found
336         $c = $c->reply->html_not_found;
337
338       Render the not found template "not_found.$mode.$format.*" or
339       "not_found.$format.*" and set the response status code to 404. Also
340       sets the stash value "snapshot" to a copy of the "stash" for use in the
341       templates.
342
343   reply->json_exception
344         $c = $c->reply->json_exception('Oops!');
345         $c = $c->reply->json_exception(Mojo::Exception->new);
346
347       Render a JSON response and set the response status to 500.
348
349   reply->json_not_found
350         $c = $c->reply->json_not_found;
351
352       Render a JSON response and set the response status to 404.
353
354   reply->not_found
355         $c = $c->reply->not_found;
356
357       Render a not found response in the appropriate format by delegating to
358       more specific exception helpers.
359
360   reply->static
361         $c->reply->static('images/logo.png');
362         $c->reply->static('../lib/MyApp.pm');
363
364       Reply with a static file using "static" in Mojolicious, usually from
365       the "public" directories or "DATA" sections of your application. Note
366       that this helper uses a relative path, but does not protect from
367       traversing to parent directories.
368
369         # Serve file from a relative path with a custom content type
370         $c->res->headers->content_type('application/myapp');
371         $c->reply->static('foo.txt');
372
373   reply->txt_exception
374         $c = $c->reply->txt_exception('Oops!');
375         $c = $c->reply->txt_exception(Mojo::Exception->new);
376
377       Render a plain text response and set the response status to 500.
378
379   reply->txt_not_found
380         $c = $c->reply->txt_not_found;
381
382       Render a plain text response and set the response status to 404.
383
384   respond_to
385         $c = $c->respond_to(
386           json => {json => {message => 'Welcome!'}},
387           html => {template => 'welcome'},
388           any  => sub {...}
389         );
390
391       Automatically select best possible representation for resource from
392       "format" "GET"/"POST" parameter, "format" stash value or "Accept"
393       request header, defaults to "default_format" in Mojolicious::Renderer
394       or rendering an empty 204 response. Each representation can be handled
395       with a callback or a hash reference containing arguments to be passed
396       to "render" in Mojolicious::Controller.
397
398         # Everything else than "json" and "xml" gets a 204 response
399         $c->respond_to(
400           json => sub { $c->render(json => {just => 'works'}) },
401           xml  => {text => '<just>works</just>'},
402           any  => {data => '', status => 204}
403         );
404
405       For more advanced negotiation logic you can also use "accepts".
406
407   session
408         %= session 'foo'
409
410       Alias for "session" in Mojolicious::Controller.
411
412   stash
413         %= stash 'foo'
414         % stash foo => 'bar';
415
416       Alias for "stash" in Mojolicious::Controller.
417
418         %= stash('name') // 'Somebody'
419
420   timing->begin
421         $c->timing->begin('foo');
422
423       Create named timestamp for "timing->elapsed".
424
425   timing->elapsed
426         my $elapsed = $c->timing->elapsed('foo');
427
428       Return fractional amount of time in seconds since named timstamp has
429       been created with "timing->begin" or "undef" if no such timestamp
430       exists.
431
432         # Log timing information
433         $c->timing->begin('database_stuff');
434         ...
435         my $elapsed = $c->timing->elapsed('database_stuff');
436         $c->app->log->debug("Database stuff took $elapsed seconds");
437
438   timing->rps
439         my $rps = $c->timing->rps('0.001');
440
441       Return fractional number of requests that could be performed in one
442       second if every singe one took the given amount of time in seconds or
443       "undef" if the number is too low.
444
445         # Log more timing information
446         $c->timing->begin('web_stuff');
447         ...
448         my $elapsed = $c->timing->elapsed('web_stuff');
449         my $rps     = $c->timing->rps($elapsed);
450         $c->app->log->debug("Web stuff took $elapsed seconds ($rps per second)");
451
452   timing->server_timing
453         $c->timing->server_timing('metric');
454         $c->timing->server_timing('metric', 'Some Description');
455         $c->timing->server_timing('metric', 'Some Description', '0.001');
456
457       Create "Server-Timing" header with optional description and duration.
458
459         # "Server-Timing: miss"
460         $c->timing->server_timing('miss');
461
462         # "Server-Timing: dc;desc=atl"
463         $c->timing->server_timing('dc', 'atl');
464
465         # "Server-Timing: db;desc=Database;dur=0.0001"
466         $c->timing->begin('database_stuff');
467         ...
468         my $elapsed = $c->timing->elapsed('database_stuff');
469         $c->timing->server_timing('db', 'Database', $elapsed);
470
471         # "Server-Timing: miss, dc;desc=atl"
472         $c->timing->server_timing('miss');
473         $c->timing->server_timing('dc', 'atl');
474
475   title
476         %= title
477         % title 'Welcome!';
478         % title 'Welcome!', foo => 'bar';
479
480       Get or set "title" stash value, all additional key/value pairs get
481       merged into the "stash".
482
483   ua
484         %= ua->get('mojolicious.org')->result->dom->at('title')->text
485
486       Alias for "ua" in Mojolicious.
487
488   url_for
489         %= url_for 'named', foo => 'bar', baz => 'yada'
490
491       Alias for "url_for" in Mojolicious::Controller.
492
493         %= url_for('/index.html')->query(foo => 'bar')
494
495   url_with
496         %= url_with 'named', foo => 'bar', baz => 'yada'
497
498       Does the same as "url_for", but inherits query parameters from the
499       current request.
500
501         %= url_with->query({page => 2})
502
503   validation
504         my $v = $c->validation;
505
506       Get Mojolicious::Validator::Validation object for current request to
507       validate file uploads as well as "GET" and "POST" parameters extracted
508       from the query string and "application/x-www-form-urlencoded" or
509       "multipart/form-data" message body. Parts of the request body need to
510       be loaded into memory to parse "POST" parameters, so you have to make
511       sure it is not excessively large. There's a 16MiB limit for requests by
512       default.
513
514         # Validate GET/POST parameter
515         my $v = $c->validation;
516         $v->required('title', 'trim')->size(3, 50);
517         my $title = $v->param('title');
518
519         # Validate file upload
520         my $v = $c->validation;
521         $v->required('tarball')->upload->size(1, 1048576);
522         my $tarball = $v->param('tarball');
523

METHODS

525       Mojolicious::Plugin::DefaultHelpers inherits all methods from
526       Mojolicious::Plugin and implements the following new ones.
527
528   register
529         $plugin->register(Mojolicious->new);
530
531       Register helpers in Mojolicious application.
532

SEE ALSO

534       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
535
536
537
538perl v5.36.0                      2023-01M-o2j0olicious::Plugin::DefaultHelpers(3)
Impressum