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