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   extends
139         % extends 'blue';
140         % extends 'blue', title => 'Blue!';
141
142       Set "extends" stash value, all additional key/value pairs get merged
143       into the "stash".
144
145   flash
146         my $foo = $c->flash('foo');
147         $c      = $c->flash({foo => 'bar'});
148         $c      = $c->flash(foo => 'bar');
149         %= flash 'foo'
150
151       Data storage persistent only for the next request, stored in the
152       "session".
153
154         # Show message after redirect
155         $c->flash(message => 'User created successfully!');
156         $c->redirect_to('show_user', id => 23);
157
158   inactivity_timeout
159         $c = $c->inactivity_timeout(3600);
160
161       Use "stream" in Mojo::IOLoop to find the current connection and
162       increase timeout if possible.
163
164         # Longer version
165         Mojo::IOLoop->stream($c->tx->connection)->timeout(3600);
166
167   include
168         %= include 'menubar'
169         %= include 'menubar', format => 'txt'
170
171       Alias for "render_to_string" in Mojolicious::Controller.
172
173   is_fresh
174         my $bool = $c->is_fresh;
175         my $bool = $c->is_fresh(etag => 'abc');
176         my $bool = $c->is_fresh(etag => 'W/"def"');
177         my $bool = $c->is_fresh(last_modified => $epoch);
178
179       Check freshness of request by comparing the "If-None-Match" and
180       "If-Modified-Since" request headers to the "ETag" and "Last-Modified"
181       response headers with "is_fresh" in Mojolicious::Static.
182
183         # Add ETag/Last-Modified headers and check freshness before rendering
184         $c->is_fresh(etag => 'abc', last_modified => 1424985708)
185           ? $c->rendered(304)
186           : $c->render(text => 'I ♥ Mojolicious!');
187
188   layout
189         % layout 'green';
190         % layout 'green', title => 'Green!';
191
192       Set "layout" stash value, all additional key/value pairs get merged
193       into the "stash".
194
195   log
196         my $log = $c->log;
197
198       Alternative to "log" in Mojolicious that includes "request_id" in
199       Mojo::Message::Request with every log message.
200
201         # Log message with context
202         $c->log->debug('This is a log message with request id');
203
204         # Pass logger with context to model
205         my $log = $c->log;
206         $c->some_model->create({foo => $foo}, $log);
207
208   param
209         %= param 'foo'
210
211       Alias for "param" in Mojolicious::Controller.
212
213   proxy->get_p
214         my $promise = $c->proxy->get_p('http://example.com' => {Accept => '*/*'});
215
216       Perform non-blocking "GET" request and forward response as efficiently
217       as possible, takes the same arguments as "get" in Mojo::UserAgent and
218       returns a Mojo::Promise object.
219
220         # Forward with exception handling
221         $c->proxy->get_p('http://mojolicious.org')->catch(sub {
222           my $err = shift;
223           $c->log->debug("Proxy error: $err");
224           $c->render(text => 'Something went wrong!', status => 400);
225         });
226
227   proxy->post_p
228         my $promise = $c->proxy->post_p('http://example.com' => {Accept => '*/*'});
229
230       Perform non-blocking "POST" request and forward response as efficiently
231       as possible, takes the same arguments as "post" in Mojo::UserAgent and
232       returns a Mojo::Promise object.
233
234         # Forward with exception handling
235         $c->proxy->post_p('example.com' => form => {test => 'pass'})->catch(sub {
236           my $err = shift;
237           $c->log->debug("Proxy error: $err");
238           $c->render(text => 'Something went wrong!', status => 400);
239         });
240
241   proxy->start_p
242         my $promise = $c->proxy->start_p(Mojo::Transaction::HTTP->new);
243
244       Perform non-blocking request for a custom Mojo::Transaction::HTTP
245       object and forward response as efficiently as possible, returns a
246       Mojo::Promise object.
247
248         # Forward with exception handling
249         my $tx = $c->ua->build_tx(GET => 'http://mojolicious.org');
250         $c->proxy->start_p($tx)->catch(sub {
251           my $err = shift;
252           $c->log->debug("Proxy error: $err");
253           $c->render(text => 'Something went wrong!', status => 400);
254         });
255
256         # Forward with custom request and response headers
257         my $headers = $c->req->headers->clone->dehop;
258         $headers->header('X-Proxy' => 'Mojo');
259         my $tx = $c->ua->build_tx(GET => 'http://example.com' => $headers->to_hash);
260         $c->proxy->start_p($tx);
261         $tx->res->content->once(body => sub {
262           $c->res->headers->header('X-Proxy' => 'Mojo');
263         });
264
265   redirect_to
266         $c = $c->redirect_to('named', foo => 'bar');
267         $c = $c->redirect_to('named', {foo => 'bar'});
268         $c = $c->redirect_to('/index.html');
269         $c = $c->redirect_to('http://example.com/index.html');
270
271       Prepare a 302 (if the status code is not already "3xx") redirect
272       response with "Location" header, takes the same arguments as "url_for".
273
274         # Moved Permanently
275         $c->res->code(301);
276         $c->redirect_to('some_route');
277
278         # Temporary Redirect
279         $c->res->code(307);
280         $c->redirect_to('some_route');
281
282   reply->asset
283         $c->reply->asset(Mojo::Asset::File->new);
284
285       Reply with a Mojo::Asset::File or Mojo::Asset::Memory object using
286       "serve_asset" in Mojolicious::Static, and perform content negotiation
287       with "Range", "If-Modified-Since" and "If-None-Match" headers.
288
289         # Serve asset with custom modification time
290         my $asset = Mojo::Asset::Memory->new;
291         $asset->add_chunk('Hello World!')->mtime(784111777);
292         $c->res->headers->content_type('text/plain');
293         $c->reply->asset($asset);
294
295         # Serve static file if it exists
296         if (my $asset = $c->app->static->file('images/logo.png')) {
297           $c->res->headers->content_type('image/png');
298           $c->reply->asset($asset);
299         }
300
301   reply->exception
302         $c = $c->reply->exception('Oops!');
303         $c = $c->reply->exception(Mojo::Exception->new);
304
305       Render the exception template "exception.$mode.$format.*" or
306       "exception.$format.*" and set the response status code to 500. Also
307       sets the stash values "exception" to a Mojo::Exception object and
308       "snapshot" to a copy of the "stash" for use in the templates.
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->not_found
327         $c = $c->reply->not_found;
328
329       Render the not found template "not_found.$mode.$format.*" or
330       "not_found.$format.*" and set the response status code to 404. Also
331       sets the stash value "snapshot" to a copy of the "stash" for use in the
332       templates.
333
334   reply->static
335         my $bool = $c->reply->static('images/logo.png');
336         my $bool = $c->reply->static('../lib/MyApp.pm');
337
338       Reply with a static file using "static" in Mojolicious, usually from
339       the "public" directories or "DATA" sections of your application. Note
340       that this helper uses a relative path, but does not protect from
341       traversing to parent directories.
342
343         # Serve file from a relative path with a custom content type
344         $c->res->headers->content_type('application/myapp');
345         $c->reply->static('foo.txt');
346
347   respond_to
348         $c = $c->respond_to(
349           json => {json => {message => 'Welcome!'}},
350           html => {template => 'welcome'},
351           any  => sub {...}
352         );
353
354       Automatically select best possible representation for resource from
355       "format" "GET"/"POST" parameter, "format" stash value or "Accept"
356       request header, defaults to "default_format" in Mojolicious::Renderer
357       or rendering an empty 204 response. Each representation can be handled
358       with a callback or a hash reference containing arguments to be passed
359       to "render" in Mojolicious::Controller.
360
361         # Everything else than "json" and "xml" gets a 204 response
362         $c->respond_to(
363           json => sub { $c->render(json => {just => 'works'}) },
364           xml  => {text => '<just>works</just>'},
365           any  => {data => '', status => 204}
366         );
367
368       For more advanced negotiation logic you can also use "accepts".
369
370   session
371         %= session 'foo'
372
373       Alias for "session" in Mojolicious::Controller.
374
375   stash
376         %= stash 'foo'
377         % stash foo => 'bar';
378
379       Alias for "stash" in Mojolicious::Controller.
380
381         %= stash('name') // 'Somebody'
382
383   timing->begin
384         $c->timing->begin('foo');
385
386       Create named timestamp for "timing->elapsed".
387
388   timing->elapsed
389         my $elapsed = $c->timing->elapsed('foo');
390
391       Return fractional amount of time in seconds since named timstamp has
392       been created with "timing->begin" or "undef" if no such timestamp
393       exists.
394
395         # Log timing information
396         $c->timing->begin('database_stuff');
397         ...
398         my $elapsed = $c->timing->elapsed('database_stuff');
399         $c->app->log->debug("Database stuff took $elapsed seconds");
400
401   timing->rps
402         my $rps = $c->timing->rps('0.001');
403
404       Return fractional number of requests that could be performed in one
405       second if every singe one took the given amount of time in seconds or
406       "undef" if the number is too low.
407
408         # Log more timing information
409         $c->timing->begin('web_stuff');
410         ...
411         my $elapsed = $c->timing->elapsed('web_stuff');
412         my $rps     = $c->timing->rps($elapsed);
413         $c->app->log->debug("Web stuff took $elapsed seconds ($rps per second)");
414
415   timing->server_timing
416         $c->timing->server_timing('metric');
417         $c->timing->server_timing('metric', 'Some Description');
418         $c->timing->server_timing('metric', 'Some Description', '0.001');
419
420       Create "Server-Timing" header with optional description and duration.
421
422         # "Server-Timing: miss"
423         $c->timing->server_timing('miss');
424
425         # "Server-Timing: dc;desc=atl"
426         $c->timing->server_timing('dc', 'atl');
427
428         # "Server-Timing: db;desc=Database;dur=0.0001"
429         $c->timing->begin('database_stuff');
430         ...
431         my $elapsed = $c->timing->elapsed('database_stuff');
432         $c->timing->server_timing('db', 'Database', $elapsed);
433
434         # "Server-Timing: miss, dc;desc=atl"
435         $c->timing->server_timing('miss');
436         $c->timing->server_timing('dc', 'atl');
437
438   title
439         %= title
440         % title 'Welcome!';
441         % title 'Welcome!', foo => 'bar';
442
443       Get or set "title" stash value, all additional key/value pairs get
444       merged into the "stash".
445
446   ua
447         %= ua->get('mojolicious.org')->result->dom->at('title')->text
448
449       Alias for "ua" in Mojolicious.
450
451   url_for
452         %= url_for 'named', controller => 'bar', action => 'baz'
453
454       Alias for "url_for" in Mojolicious::Controller.
455
456         %= url_for('/index.html')->query(foo => 'bar')
457
458   url_with
459         %= url_with 'named', controller => 'bar', action => 'baz'
460
461       Does the same as "url_for", but inherits query parameters from the
462       current request.
463
464         %= url_with->query({page => 2})
465
466   validation
467         my $v = $c->validation;
468
469       Get Mojolicious::Validator::Validation object for current request to
470       validate file uploads as well as "GET" and "POST" parameters extracted
471       from the query string and "application/x-www-form-urlencoded" or
472       "multipart/form-data" message body. Parts of the request body need to
473       be loaded into memory to parse "POST" parameters, so you have to make
474       sure it is not excessively large. There's a 16MiB limit for requests by
475       default.
476
477         # Validate GET/POST parameter
478         my $v = $c->validation;
479         $v->required('title', 'trim')->size(3, 50);
480         my $title = $v->param('title');
481
482         # Validate file upload
483         my $v = $c->validation;
484         $v->required('tarball')->upload->size(1, 1048576);
485         my $tarball = $v->param('tarball');
486

METHODS

488       Mojolicious::Plugin::DefaultHelpers inherits all methods from
489       Mojolicious::Plugin and implements the following new ones.
490
491   register
492         $plugin->register(Mojolicious->new);
493
494       Register helpers in Mojolicious application.
495

SEE ALSO

497       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
498
499
500
501perl v5.32.0                      2020-07M-o2j8olicious::Plugin::DefaultHelpers(3)
Impressum