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 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 ($err) {
222 $c->log->debug("Proxy error: $err");
223 $c->render(text => 'Something went wrong!', status => 400);
224 });
225
226 proxy->post_p
227 my $promise = $c->proxy->post_p('http://example.com' => {Accept => '*/*'});
228
229 Perform non-blocking "POST" request and forward response as efficiently
230 as possible, takes the same arguments as "post" in Mojo::UserAgent and
231 returns a Mojo::Promise object.
232
233 # Forward with exception handling
234 $c->proxy->post_p('example.com' => form => {test => 'pass'})->catch(sub ($err) {
235 $c->log->debug("Proxy error: $err");
236 $c->render(text => 'Something went wrong!', status => 400);
237 });
238
239 proxy->start_p
240 my $promise = $c->proxy->start_p(Mojo::Transaction::HTTP->new);
241
242 Perform non-blocking request for a custom Mojo::Transaction::HTTP
243 object and forward response as efficiently as possible, returns a
244 Mojo::Promise object.
245
246 # Forward with exception handling
247 my $tx = $c->ua->build_tx(GET => 'http://mojolicious.org');
248 $c->proxy->start_p($tx)->catch(sub ($err) {
249 $c->log->debug("Proxy error: $err");
250 $c->render(text => 'Something went wrong!', status => 400);
251 });
252
253 # Forward with custom request and response headers
254 my $headers = $c->req->headers->clone->dehop;
255 $headers->header('X-Proxy' => 'Mojo');
256 my $tx = $c->ua->build_tx(GET => 'http://example.com' => $headers->to_hash);
257 $c->proxy->start_p($tx);
258 $tx->res->content->once(body => sub ($content) { $c->res->headers->header('X-Proxy' => 'Mojo') });
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 $c->reply->static('images/logo.png');
331 $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', foo => 'bar', baz => 'yada'
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', foo => 'bar', baz => 'yada'
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.34.0 2021-07M-o2j2olicious::Plugin::DefaultHelpers(3)