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