View on
MetaCPAN
search.cpan.org is shutting down
For details read Perl NOC. After June 25th this page will redirect to MetaCPAN.org
Sebastian Riedel > Mojolicious > Mojolicious::Plugin::DefaultHelpers

Download:
Mojolicious-7.85.tar.gz

Dependencies

Annotate this POD

Website

View/Report Bugs
Source  

NAME ^

Mojolicious::Plugin::DefaultHelpers - Default helpers plugin

SYNOPSIS ^

  # Mojolicious
  $app->plugin('DefaultHelpers');

  # Mojolicious::Lite
  plugin 'DefaultHelpers';

DESCRIPTION ^

Mojolicious::Plugin::DefaultHelpers is a collection of helpers for Mojolicious.

This is a core plugin, that means it is always enabled and its code a good example for learning to build new plugins, you're welcome to fork it.

See "PLUGINS" in Mojolicious::Plugins for a list of plugins that are available by default.

HELPERS ^

Mojolicious::Plugin::DefaultHelpers implements the following helpers.

accepts

  my $formats = $c->accepts;
  my $format  = $c->accepts('html', 'json', 'txt');

Select best possible representation for resource from format GET/POST parameter, format stash value or Accept request header with "accepts" in Mojolicious::Renderer, defaults to returning the first extension if no preference could be detected.

  # Check if JSON is acceptable
  $c->render(json => {hello => 'world'}) if $c->accepts('json');

  # Check if JSON was specifically requested
  $c->render(json => {hello => 'world'}) if $c->accepts('', 'json');

  # Unsupported representation
  $c->render(data => '', status => 204)
    unless my $format = $c->accepts('html', 'json');

  # Detected representations to select from
  my @formats = @{$c->accepts};

app

  %= app->secrets->[0]

Alias for "app" in Mojolicious::Controller.

b

  %= b('Joel is a slug')->slugify

Turn string into a Mojo::ByteStream object.

c

  %= c('a', 'b', 'c')->shuffle->join

Turn list into a Mojo::Collection object.

config

  %= config 'something'

Alias for "config" in Mojolicious.

content

  %= content foo => begin
    test
  % end
  %= content bar => 'Hello World!'
  %= content 'foo'
  %= content 'bar'
  %= content

Store partial rendered content in a named buffer and retrieve it later, defaults to retrieving the named buffer content, which is used by the renderer for the layout and extends features. New content will be ignored if the named buffer is already in use.

content_for

  % content_for foo => begin
    test
  % end
  %= content_for 'foo'

Same as "content", but appends content to named buffers if they are already in use.

  % content_for message => begin
    Hello
  % end
  % content_for message => begin
    world!
  % end
  %= content 'message'

content_with

  % content_with foo => begin
    test
  % end
  %= content_with 'foo'

Same as "content", but replaces content of named buffers if they are already in use.

  % content message => begin
    world!
  % end
  % content_with message => begin
    Hello <%= content 'message' %>
  % end
  %= content 'message'

csrf_token

  %= csrf_token

Get CSRF token from "session", and generate one if none exists.

current_route

  % if (current_route 'login') {
    Welcome to Mojolicious!
  % }
  %= current_route

Check or get name of current route.

dumper

  %= dumper {some => 'data'}

Dump a Perl data structure with "dumper" in Mojo::Util, very useful for debugging.

extends

  % extends 'blue';
  % extends 'blue', title => 'Blue!';

Set extends stash value, all additional key/value pairs get merged into the "stash".

flash

  %= flash 'foo'

Alias for "flash" in Mojolicious::Controller.

inactivity_timeout

  $c = $c->inactivity_timeout(3600);

Use "stream" in Mojo::IOLoop to find the current connection and increase timeout if possible.

  # Longer version
  Mojo::IOLoop->stream($c->tx->connection)->timeout(3600);

include

  %= include 'menubar'
  %= include 'menubar', format => 'txt'

Alias for "render_to_string" in Mojolicious::Controller.

is_fresh

  my $bool = $c->is_fresh;
  my $bool = $c->is_fresh(etag => 'abc');
  my $bool = $c->is_fresh(last_modified => $epoch);

Check freshness of request by comparing the If-None-Match and If-Modified-Since request headers to the ETag and Last-Modified response headers with "is_fresh" in Mojolicious::Static.

  # Add ETag/Last-Modified headers and check freshness before rendering
  $c->is_fresh(etag => 'abc', last_modified => 1424985708)
    ? $c->rendered(304)
    : $c->render(text => 'I ♥ Mojolicious!');

layout

  % layout 'green';
  % layout 'green', title => 'Green!';

Set layout stash value, all additional key/value pairs get merged into the "stash".

param

  %= param 'foo'

Alias for "param" in Mojolicious::Controller.

reply->asset

  $c->reply->asset(Mojo::Asset::File->new);

Reply with a Mojo::Asset::File or Mojo::Asset::Memory object using "serve_asset" in Mojolicious::Static, and perform content negotiation with Range, If-Modified-Since and If-None-Match headers.

  # Serve asset with custom modification time
  my $asset = Mojo::Asset::Memory->new;
  $asset->add_chunk('Hello World!')->mtime(784111777);
  $c->res->headers->content_type('text/plain');
  $c->reply->asset($asset);

  # Serve static file if it exists
  if (my $asset = $c->app->static->file('images/logo.png')) {
    $c->res->headers->content_type('image/png');
    $c->reply->asset($asset);
  }

reply->exception

  $c = $c->reply->exception('Oops!');
  $c = $c->reply->exception(Mojo::Exception->new);

Render the exception template exception.$mode.$format.* or exception.$format.* and set the response status code to 500. Also sets the stash values exception to a Mojo::Exception object and snapshot to a copy of the "stash" for use in the templates.

reply->file

  $c->reply->file('/etc/passwd');

Reply with a static file from an absolute path anywhere on the file system using "static" in Mojolicious.

  # Longer version
  $c->reply->asset(Mojo::Asset::File->new(path => '/etc/passwd'));

  # Serve file from an absolute path with a custom content type
  $c->res->headers->content_type('application/myapp');
  $c->reply->file('/home/sri/foo.txt');

  # Serve file from a secret application directory
  $c->reply->file($c->app->home->child('secret', 'file.txt'));

reply->not_found

  $c = $c->reply->not_found;

Render the not found template not_found.$mode.$format.* or not_found.$format.* and set the response status code to 404. Also sets the stash value snapshot to a copy of the "stash" for use in the templates.

reply->static

  my $bool = $c->reply->static('images/logo.png');
  my $bool = $c->reply->static('../lib/MyApp.pm');

Reply with a static file using "static" in Mojolicious, usually from the public directories or DATA sections of your application. Note that this helper uses a relative path, but does not protect from traversing to parent directories.

  # Serve file from a relative path with a custom content type
  $c->res->headers->content_type('application/myapp');
  $c->reply->static('foo.txt');

session

  %= session 'foo'

Alias for "session" in Mojolicious::Controller.

stash

  %= stash 'foo'
  % stash foo => 'bar';

Alias for "stash" in Mojolicious::Controller.

  %= stash('name') // 'Somebody'

timing->begin

  $c->timing->begin('foo');

Create named timestamp for "timing->elapsed". Note that this helper is EXPERIMENTAL and might change without warning!

timing->elapsed

  my $elapsed = $c->timing->elapsed('foo');

Return fractional amount of time in seconds since named timstamp has been created with "timing->begin" or undef if no such timestamp exists. Note that this helper is EXPERIMENTAL and might change without warning!

  # Log timing information
  $c->timing->begin('database_stuff');
  ...
  my $elapsed = $c->timing->elapsed('database_stuff');
  $c->app->log->debug("Database stuff took $elapsed seconds");

timing->rps

  my $rps = $c->timing->rps('0.001');

Return fractional number of requests that could be performed in one second if every singe one took the given amount of time in seconds or undef if the number is too low. Note that this helper is EXPERIMENTAL and might change without warning!

  # Log more timing information
  $c->timing->begin('web_stuff');
  ...
  my $elapsed = $c->timing->elapsed('web_stuff');
  my $rps     = $c->timing->rps($elapsed);
  $c->app->log->debug("Web stuff took $elapsed seconds ($rps per second)");

timing->server_timing

  $c->timing->server_timing('metric');
  $c->timing->server_timing('metric', 'Some Description');
  $c->timing->server_timing('metric', 'Some Description', '0.001');

Create Server-Timing header with optional description and duration. Note that this helper is EXPERIMENTAL and might change without warning!

  # "Server-Timing: miss"
  $c->timing->server_timing('miss');

  # "Server-Timing: dc;desc=atl"
  $c->timing->server_timing('dc', 'atl');

  # "Server-Timing: db;desc=Database;dur=0.0001"
  $c->timing->begin('database_stuff');
  ...
  my $elapsed = $c->timing->elapsed('database_stuff');
  $c->timing->server_timing('db', 'Database', $elapsed);

  # "Server-Timing: miss, dc;desc=atl"
  $c->timing->server_timing('miss');
  $c->timing->server_timing('dc', 'atl');

title

  %= title
  % title 'Welcome!';
  % title 'Welcome!', foo => 'bar';

Get or set title stash value, all additional key/value pairs get merged into the "stash".

ua

  %= ua->get('mojolicious.org')->result->dom->at('title')->text

Alias for "ua" in Mojolicious.

url_for

  %= url_for 'named', controller => 'bar', action => 'baz'

Alias for "url_for" in Mojolicious::Controller.

  %= url_for('/index.html')->query(foo => 'bar')

url_with

  %= url_with 'named', controller => 'bar', action => 'baz'

Does the same as "url_for", but inherits query parameters from the current request.

  %= url_with->query([page => 2])

validation

  %= validation->param('foo')

Alias for "validation" in Mojolicious::Controller.

METHODS ^

Mojolicious::Plugin::DefaultHelpers inherits all methods from Mojolicious::Plugin and implements the following new ones.

register

  $plugin->register(Mojolicious->new);

Register helpers in Mojolicious application.

SEE ALSO ^

Mojolicious, Mojolicious::Guides, https://mojolicious.org.

syntax highlighting: