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