Yuki Kimoto add files
aa0f2e9 10 years ago
1 contributor
1180 lines | 32.593kb
=encoding utf8

=head1 NAME

Mojolicious::Guides::Rendering - Rendering

=head1 OVERVIEW

This document explains content generation with the L<Mojolicious> renderer.

=head1 CONCEPTS

Essentials every L<Mojolicious> developer should know.

=head2 Renderer

The renderer is a tiny black box turning stash data into actual responses
utilizing multiple template systems and data encoding modules.

  {text => 'Hello.'}                 -> 200 OK, text/html, 'Hello.'
  {json => {x => 3}}                 -> 200 OK, application/json, '{"x":3}'
  {text => 'Oops.', status => '410'} -> 410 Gone, text/html, 'Oops.'

Templates can be automatically detected if enough information is provided by
the developer or routes. Template names are expected to follow the
C<name.format.handler> scheme, with C<name> defaulting to C<controller/action>
or the route name, C<format> defaulting to C<html> and C<handler> to C<ep>.

  {controller => 'users', action => 'list'} -> 'users/list.html.ep'
  {name => 'foo', format => 'txt'}          -> 'foo.txt.ep'
  {name => 'foo', handler => 'epl'}         -> 'foo.html.epl'

All templates should be in the C<templates> directories of the application or
the C<DATA> section of the class C<main>.

  __DATA__

  @@ time.html.ep
  % use Time::Piece;
  % my $now = localtime;
  <!DOCTYPE html>
  <html>
    <head><title>Time</title></head>
    <body>The time is <%= $now->hms %>.</body>
  </html>

  @@ hello.txt.ep
  ...

The renderer can be easily extended to support additional template systems
with plugins, but more about that later.

=head2 Embedded Perl

L<Mojolicious> includes a minimalistic but very powerful template system out
of the box called Embedded Perl or C<ep> for short. It allows the embedding of
Perl code right into actual content using a small set of special tags and line
start characters.

  <% Perl code %>
  <%= Perl expression, replaced with XML escaped result %>
  <%== Perl expression, replaced with result %>
  <%# Comment, useful for debugging %>
  <%% Replaced with "<%", useful for generating templates %>
  % Perl code line, treated as "<% line =%>"
  %= Perl expression line, treated as "<%= line %>"
  %== Perl expression line, treated as "<%== line %>"
  %# Comment line, useful for debugging
  %% Replaced with "%", useful for generating templates

Tags and lines work pretty much the same, but depending on context one will
usually look a bit better. Semicolons get automatically appended to all
expressions.

  <% my $i = 10; %>
  <ul>
    <% for my $j (1 .. $i) { %>
      <li>
        <%= $j %>
      </li>
    <% } %>
  </ul>

  % my $i = 10;
  <ul>
    % for my $j (1 .. $i) {
      <li>
        %= $j
      </li>
    % }
  </ul>

Aside from differences in whitespace handling, both examples generate similar
Perl code, a naive translation could look like this.

  my $output = '';
  my $i = 10;
  $output .= '<ul>';
  for my $j (1 .. $i) {
    $output .= '<li>';
    $output .= xml_escape scalar $j;
    $output .= '</li>';
  }
  $output .= '</ul>';
  return $output;

An additional equal sign can be used to disable escaping of the characters
C<E<lt>>, C<E<gt>>, C<&>, C<'> and C<"> in results from Perl expressions,
which is the default to prevent XSS attacks against your application.

  <%= 'lalala' %>
  <%== '<p>test</p>' %>

Only L<Mojo::ByteStream> objects are excluded from automatic escaping.

  % use Mojo::ByteStream 'b';
  <%= b('<p>test</p>') %>

Newline characters can be escaped with a backslash.

  This is <%= 1 + 1 %> a\
  single line

And a backslash in front of a newline character can be escaped with another
backslash.

  This will <%= 1 + 1 %> result\\
  in multiple\\
  lines

You can also add an additional equal sign to the end of a tag to have it
automatically remove all surrounding whitespace, this allows free indenting
without ruining the result.

  <% for (1 .. 3) { %>
    <%= $foo =%>
  <% } %>

Stash values that don't have invalid characters in their name get
automatically initialized as normal variables in the template, and the
controller object as C<$self>.

  $self->stash(name => 'tester');

  Hello <%= $name %> from <%= $self->tx->remote_address %>.

There are also many helper functions available, but more about that later.

  <%= dumper {foo => 'bar'} %>

=head1 BASICS

Most commonly used features every L<Mojolicious> developer should know about.

=head2 Automatic rendering

The renderer can be manually started by calling the method
L<Mojolicious::Controller/"render">, but that's usually not necessary,
because it will get automatically called if nothing has been rendered after
the router finished its work. This also means you can have routes pointing
only to templates without actual actions.

  $self->render;

There is one big difference though, by calling it manually you can make sure
that templates use the current controller object, and not the default
controller specified with the attribute L<Mojolicious/"controller_class">.

  $self->render_later;

You can also disable automatic rendering with the method
L<Mojolicious::Controller/"render_later">, which can be very useful to delay
rendering when a non-blocking operation has to be performed first.

=head2 Rendering templates

The renderer will always try to detect the right template, but you can also
use the C<template> stash value to render a specific one. Everything before
the last slash will be interpreted as the subdirectory path in which to find
the template.

  # foo/bar/baz.*.*
  $self->render(template => 'foo/bar/baz');

Choosing a specific C<format> and C<handler> is just as easy.

  # foo/bar/baz.txt.epl
  $self->render(template => 'foo/bar/baz', format => 'txt', handler => 'epl');

Because rendering a specific template is the most common task it also has a
shortcut.

  $self->render('foo/bar/baz');

If you're not sure in advance if a template actually exists, you can also use
the method L<Mojolicious::Controller/"render_maybe"> to try multiple
alternatives.

  $self->render_maybe('localized/baz') or $self->render('foo/bar/baz');

=head2 Rendering inline templates

Some renderers such as C<ep> allow templates to be passed inline.

  $self->render(inline => 'The result is <%= 1 + 1 %>.');

Since auto detection depends on a path you might have to supply a C<handler>
too.

  $self->render(inline => "<%= shift->param('foo') %>", handler => 'epl');

=head2 Rendering text

Characters can be rendered to bytes with the C<text> stash value, the given
content will be automatically encoded to bytes.

  $self->render(text => 'I ♥ Mojolicious!');

=head2 Rendering data

Bytes can be rendered with the C<data> stash value, no encoding will be
performed.

  $self->render(data => $bytes);

=head2 Rendering JSON

The C<json> stash value allows you to pass Perl data structures to the
renderer which get directly encoded to JSON.

  $self->render(json => {foo => [1, 'test', 3]});

=head2 Partial rendering

Sometimes you might want to use the rendered result directly instead of
generating a response, for example to send emails, this can be done using the
C<partial> stash value.

  my $html = $self->render('mail', partial => 1);

No encoding will be performed, making it easy to reuse the result in other
templates or to generate binary data.

  my $pdf = $self->render('invoice', format => 'pdf', partial => 1);
  $self->render(data => $pdf, format => 'pdf');

=head2 Status code

Response status codes can be changed with the C<status> stash value.

  $self->render(text => 'Oops.', status => 500);

=head2 Content type

The C<Content-Type> header of the response is actually based on the MIME type
mapping of the C<format> stash value.

  # Content-Type: text/plain
  $self->render(text => 'Hello.', format => 'txt');

  # Content-Type: image/png
  $self->render(data => $bytes, format => 'png');

These mappings can be easily extended or changed with L<Mojolicious/"types">.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Add new MIME type
    $self->types->type(txt => 'text/plain; charset=utf-8');
  }

  1;

=head2 Stash data

Any of the native Perl data types can be passed to templates through the
L<Mojolicious::Controller/"stash">.

  $self->stash(author     => 'Sebastian');
  $self->stash(frameworks => [qw(Catalyst Mojolicious)]);
  $self->stash(examples   => {tweetylicious => 'a microblogging app'});

  %= $author
  %= $frameworks->[1]
  %= $examples->{tweetylicious}

Since everything is just Perl normal control structures just work.

  % for my $framework (@$frameworks) {
    <%= $framework %> was written by <%= $author %>.
  % }

  % while (my ($app, $description) = each %$examples) {
    <%= $app %> is a <%= $description %>.
  % }

=head2 Content negotiation

For resources with different representations and that require truly
C<RESTful> content negotiation you can also use
L<Mojolicious::Controller/"respond_to"> instead of
L<Mojolicious::Controller/"render">.

  # /hello (Accept: application/json) -> "json"
  # /hello (Accept: application/xml)  -> "xml"
  # /hello.json                       -> "json"
  # /hello.xml                        -> "xml"
  # /hello?format=json                -> "json"
  # /hello?format=xml                 -> "xml"
  $self->respond_to(
    json => {json => {hello => 'world'}},
    xml  => {text => '<hello>world</hello>'}
  );

The best possible representation will be automatically selected from the
C<Accept> request header, C<format> stash value or C<format> GET/POST
parameter and stored in the C<format> stash value. To change MIME type
mappings for the C<Accept> request header or the C<Content-Type> response
header you can use L<Mojolicious/"types">.

  $self->respond_to(
    json => {json => {hello => 'world'}},
    html => sub {
      $self->content_for(head => '<meta name="author" content="sri">');
      $self->render(template => 'hello', message => 'world')
    }
  );

Callbacks can be used for representations that are too complex to fit into a
single render call.

  # /hello (Accept: application/json) -> "json"
  # /hello (Accept: text/html)        -> "html"
  # /hello (Accept: image/png)        -> "any"
  # /hello.json                       -> "json"
  # /hello.html                       -> "html"
  # /hello.png                        -> "any"
  # /hello?format=json                -> "json"
  # /hello?format=html                -> "html"
  # /hello?format=png                 -> "any"
  $self->respond_to(
    json => {json => {hello => 'world'}},
    html => {template => 'hello', message => 'world'},
    any  => {text => '', status => 204}
  );

And if no viable representation could be found, the C<any> fallback will be
used or an empty C<204> response rendered automatically.

=head2 Rendering C<exception> and C<not_found> pages

By now you've probably already encountered the built-in 404 (Not Found) and
500 (Server Error) pages, that get rendered automatically when you make a
mistake. Especially during development they can be a great help, you can
render them manually with the methods
L<Mojolicious::Controller/"render_exception"> and
L<Mojolicious::Controller/"render_not_found">.

  use Mojolicious::Lite;
  use Scalar::Util 'looks_like_number';

  get '/divide/:dividend/by/:divisor' => sub {
    my $self = shift;
    my ($dividend, $divisor) = $self->param(['dividend', 'divisor']);

    # 404
    return $self->render_not_found
      unless looks_like_number $dividend && looks_like_number $divisor;

    # 500
    return $self->render_exception('Division by zero!') if $divisor == 0;

    # 200
    $self->render(text => $dividend / $divisor);
  };

  app->start;

You can also change the templates of those pages, since you most likely want
to show your users something more closely related to your application in
production. The renderer will always try to find C<exception.$mode.$format.*>
or C<not_found.$mode.$format.*> before falling back to the built-in default
templates.

  @@ exception.production.html.ep
  <!DOCTYPE html>
  <html>
    <head><title>Server error</title></head>
    <body>
      <h1>Exception</h1>
      <p><%= $exception->message %></p>
      <h1>Stash</h1>
      <pre><%= dumper $snapshot %></pre>
    </body>
  </html>

=head2 Helpers

Helpers are little functions you can use in templates and controller code.

  %= dumper [1, 2, 3]

  my $serialized = $self->dumper([1, 2, 3]);

The helper L<Mojolicious::Plugin::DefaultHelpers/"dumper"> for example will
use L<Data::Dumper> to serialize whatever data structure you pass it, this can
be very useful for debugging. We differentiate between C<default helpers>
which are more general purpose like C<dumper> and C<tag helpers>, which are
template specific and mostly used to generate C<HTML> tags.

  %= javascript '/script.js'

  %= javascript begin
    var a = 'b';
  % end

A list of all built-in helpers can be found in
L<Mojolicious::Plugin::DefaultHelpers> and L<Mojolicious::Plugin::TagHelpers>.

=head2 Layouts

Most of the time when using C<ep> templates you will want to wrap your
generated content in a HTML skeleton, thanks to layouts that's absolutely
trivial.

  @@ foo/bar.html.ep
  % layout 'mylayout';
  Hello World!

  @@ layouts/mylayout.html.ep
  <!DOCTYPE html>
  <html>
    <head><title>MyApp</title></head>
    <body><%= content %></body>
  </html>

You just select the right layout template with the helper
L<Mojolicious::Plugin::DefaultHelpers/"layout"> and place the result of the
current template with the helper
L<Mojolicious::Plugin::DefaultHelpers/"content">. You can also pass along
normal stash values to the C<layout> helper.

  @@ foo/bar.html.ep
  % layout 'mylayout', title => 'Hi there';
  Hello World!

  @@ layouts/mylayout.html.ep
  <!DOCTYPE html>
  <html>
    <head><title><%= $title %></title></head>
    <body><%= content %></body>
  </html>

Instead of the C<layout> helper you could also just use the C<layout> stash
value, or call L<Mojolicious::Controller/"render"> with the C<layout>
argument.

  $self->render(template => 'mytemplate', layout => 'mylayout');

To set a C<layout> stash value application wide you can use
L<Mojolicious/"defaults">.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Default layout
    $self->defaults(layout => 'mylayout');
  }

  1;

=head2 Including partial templates

Like most helpers L<Mojolicious::Plugin::DefaultHelpers/"include"> is just a
shortcut to make your life a little easier.

  @@ foo/bar.html.ep
  <!DOCTYPE html>
  <html>
    %= include 'header'
    <body>Bar</body>
  </html>

  @@ header.html.ep
  <head><title>Howdy</title></head>

Instead of C<include> you could also just call
L<Mojolicious::Controller/"render"> with the C<partial> argument.

  @@ foo/bar.html.ep
  <!DOCTYPE html>
  <html>
    %= $self->render('header', partial => 1)
    <body>Bar</body>
  </html>

  @@ header.html.ep
  <head><title>Howdy</title></head>

But there is one small difference between the two, if you pass stash values to
C<include>, they will get localized automatically and are only available in
the partial template.

  @@ foo/bar.html.ep
  <!DOCTYPE html>
  <html>
    %= include 'header', title => 'Hello'
    <body>Bar</body>
  </html>

  @@ header.html.ep
  <head><title><%= $title %></title></head>

=head2 Reusable template blocks

It's never fun to repeat yourself, that's why you can build reusable template
blocks in C<ep> that work very similar to normal Perl functions.

  @@ welcome.html.ep
  <% my $block = begin %>
    <% my $name = shift; %>
    Hello <%= $name %>.
  <% end %>
  <%= $block->('Sebastian') %>
  <%= $block->('Sara') %>

Blocks are always delimited by the C<begin> and C<end> keywords.

  @@ welcome.html.ep
  % my $block = begin
    % my $name = shift;
    Hello <%= $name %>.
  % end
  % for (1 .. 10) {
    %== $block->('Sebastian')
  % }

A naive translation to Perl code could look like this.

  @@ welcome.html.pl
  my $output = '';
  my $block  = sub {
    my $name   = shift;
    my $output = '';
    $output .= 'Hello ';
    $output .= xml_escape scalar $name;
    $output .= '.';
    return Mojo::ByteStream->new($output);
  }
  for (1 .. 10) {
    $output .= scalar $block->('Sebastian');
  }
  return $output;

=head2 Content blocks

Blocks and the helper L<Mojolicious::Plugin::DefaultHelpers/"content_for">
can also be used to pass whole sections of the template to the layout.

  @@ foo/bar.html.ep
  % layout 'mylayout';
  % content_for header => begin
    <meta http-equiv="Content-Type" content="text/html">
  % end
  <div>Hello World!</div>
  % content_for header => begin
    <meta http-equiv="Pragma" content="no-cache">
  % end

  @@ layouts/mylayout.html.ep
  <!DOCTYPE html>
  <html>
    <head><%= content_for 'header' %></head>
    <body><%= content %></body>
  </html>

=head2 Template inheritance

Inheritance takes the layout concept above one step further, the helpers
L<Mojolicious::Plugin::DefaultHelpers/"content"> and
L<Mojolicious::Plugin::DefaultHelpers/"extends"> allow you to build a skeleton
template with named blocks that child templates can override.

  @@ first.html.ep
  <!DOCTYPE html>
  <html>
    <head><title>Hello</title></head>
    <body>
      %= content header => begin
        Default header
      % end
      <div>Hello World!</div>
      %= content footer => begin
        Default footer
      % end
    </body>
  </html>

  @@ second.html.ep
  % extends 'first';
  % content header => begin
    New header
  % end

This chain could go on and on to allow a very high level of template reuse.

=head2 Form validation

You can use L<Mojolicious::Controller/"validation"> to validate GET/POST
parameters submitted to your application. All unknown fields will be ignored
by default, so you have to decide which should be required or optional before
you can perform checks on their values. Every check is performed right away,
so you can use the results immediately to build more advanced validation logic
with methods like L<Mojolicious::Validator::Validation/"is_valid">.

  use Mojolicious::Lite;

  get '/' => sub {
    my $self = shift;

    # Check if parameters have been submitted
    my $validation = $self->validation;
    return $self->render unless $validation->has_data;

    # Validate parameters ("pass_again" depends on "pass")
    $validation->required('user')->size(1, 20)->like(qr/^[e-t]+$/);
    $validation->required('pass_again')->equal_to('pass')
      if $validation->optional('pass')->size(7, 500)->is_valid;

    # Render confirmation if validation was successful
    $self->render('thanks') unless $validation->has_error;
  } => 'index';

  app->start;
  __DATA__

  @@ index.html.ep
  <!DOCTYPE html>
  <html>
    <head>
      %= stylesheet begin
        label.field-with-error { color: #dd7e5e }
        input.field-with-error { background-color: #fd9e7e }
      % end
    </head>
    <body>
      %= form_for index => begin
        %= label_for user => 'Username (required, 1-20 characters, only e-t)'
        <br>
        %= text_field 'user'
        %= submit_button
        <br>
        %= label_for pass => 'Password (optional, 7-500 characters)'
        <br>
        %= password_field 'pass'
        <br>
        %= label_for pass_again => 'Password again (equal to the value above)'
        <br>
        %= password_field 'pass_again'
      % end
    </body>
  </html>

  @@ thanks.html.ep
  <!DOCTYPE html>
  <html><body>Thank you <%= validation->param('user') %>.</body></html>

Form elements generated with tag helpers from
L<Mojolicious::Plugin::TagHelpers> will automatically remember their previous
values and add the class C<field-with-error> for fields that failed validation
to make styling with CSS easier.

  <label class="field-with-error" for="user">
    Username (required, only characters e-t)
  </label>
  <input class="field-with-error" type="text" name="user" value="sri" />

For a full list of available checks see also
L<Mojolicious::Validator/"CHECKS">.

=head2 Adding form validation checks

Validation checks can be registered with L<Mojolicious::Validator/"add_check">
and return a false value if they were successful. A true value may be used to
pass along additional information which can then be retrieved with
L<Mojolicious::Validator::Validation/"error">.

  use Mojolicious::Lite;

  # Add "range" check
  app->validator->add_check(range => sub {
    my ($validation, $name, $value, $min, $max) = @_;
    return $value < $min || $value > $max;
  });

  get '/' => 'form';

  post '/test' => sub {
    my $self = shift;

    # Validate parameters with custom check
    my $validation = $self->validation;
    $validation->required('number')->range(3, 23);

    # Render form again if validation failed
    return $self->render('form') if $validation->has_error;

    # Prevent double submit with redirect
    $self->flash(number => $validation->param('number'));
    $self->redirect_to('form');
  };

  app->start;
  __DATA__

  @@ form.html.ep
  <!DOCTYPE html>
  <html>
    <body>
      % if (my $number = flash 'number') {
        <p>Thanks, the number <%= $number %> was valid.</p>
      % }
      %= form_for test => begin
        % if (my $err = validation->error('number')) {
          <p>
            %= 'Value is required.' if $err->[0] eq 'required'
            %= 'Value needs to be between 3 and 23.' if $err->[0] eq 'range'
          </p>
        % }
        %= text_field 'number'
        %= submit_button
      % end
    </html>
  </html>

=head2 Adding helpers

Adding and redefining helpers is very easy, you can use them to do pretty much
everything.

  use Mojolicious::Lite;

  helper debug => sub {
    my ($self, $str) = @_;
    $self->app->log->debug($str);
  };

  get '/' => sub {
    my $self = shift;
    $self->debug('Hello from an action!');
  } => 'index';

  app->start;
  __DATA__

  @@ index.html.ep
  % debug 'Hello from a template!';

Helpers can also accept template blocks as last argument, this for example
allows very pleasant to use tag helpers and filters.

  use Mojolicious::Lite;
  use Mojo::ByteStream;

  helper trim_newline => sub {
    my ($self, $block) = @_;
    my $result = $block->();
    $result =~ s/\n//g;
    return Mojo::ByteStream->new($result);
  };

  get '/' => 'index';

  app->start;
  __DATA__

  @@ index.html.ep
  %= trim_newline begin
    Some text.
    %= 1 + 1
    More text.
  % end

Wrapping the helper result into a L<Mojo::ByteStream> object can prevent
accidental double escaping.

=head2 Helper plugins

Some helpers might be useful enough for you to share them between multiple
applications, plugins make that very simple.

  package Mojolicious::Plugin::DebugHelper;
  use Mojo::Base 'Mojolicious::Plugin';

  sub register {
    my ($self, $app) = @_;
    $app->helper(debug => sub {
      my ($self, $str) = @_;
      $self->app->log->debug($str);
    });
  }

  1;

The C<register> method will be called when you load the plugin and to add your
helper to the application you can use L<Mojolicious/"helper">.

  use Mojolicious::Lite;

  plugin 'DebugHelper';

  get '/' => sub {
    my $self = shift;
    $self->debug('It works.');
    $self->render(text => 'Hello.');
  };

  app->start;

A skeleton for a full CPAN compatible plugin distribution can be automatically
generated.

  $ mojo generate plugin DebugHelper

And if you have a C<PAUSE> account (which can be requested at
L<http://pause.perl.org>), you are only a few commands away from releasing it
to CPAN.

  $ perl Makefile.PL
  $ make test
  $ make manifest
  $ make dist
  $ mojo cpanify -u USER -p PASS Mojolicious-Plugin-DebugHelper-0.01.tar.gz

=head2 Bundling assets with plugins

Assets such as templates and static files can be easily bundled with your
plugins, even if you plan to release them to CPAN.

  $ mojo generate plugin AlertAssets
  $ mkdir AlertAssets/lib/Mojolicious/Plugin/AlertAssets
  $ cd AlertAssets/lib/Mojolicious/Plugin/AlertAssets
  $ mkdir public
  $ echo 'alert("Hello World!");' > public/alertassets.js
  $ mkdir templates
  $ echo '%= javascript "/alertassets.js"' > templates/alertassets.html.ep

Just append their respective directories to the list of search paths when
C<register> is called.

  package Mojolicious::Plugin::AlertAssets;
  use Mojo::Base 'Mojolicious::Plugin';

  use File::Basename 'dirname';
  use File::Spec::Functions 'catdir';

  sub register {
    my ($self, $app) = @_;

    # Append "templates" and "public" directories
    my $base = catdir(dirname(__FILE__), 'AlertAssets');
    push @{$app->renderer->paths}, catdir($base, 'templates');
    push @{$app->static->paths},   catdir($base, 'public');
  }

  1;

Both will work just like normal C<templates> and C<public> directories once
you've installed and loaded the plugin, with slightly lower precedence.

  use Mojolicious::Lite;

  plugin 'AlertAssets';

  get '/alert_me';

  app->start;
  __DATA__

  @@ alert_me.html.ep
  <!DOCTYPE html>
  <html>
    <head>
      <title>Alert me!</title>
      %= include 'alertassets'
    </head>
    <body>You've been alerted.</body>
  </html>

And it works just the same for assets bundled in the C<DATA> section of your
plugin.

  package Mojolicious::Plugin::AlertAssets;
  use Mojo::Base 'Mojolicious::Plugin';

  sub register {
    my ($self, $app) = @_;

    # Append class
    push @{$app->renderer->classes}, __PACKAGE__;
    push @{$app->static->classes},   __PACKAGE__;
  }

  1;
  __DATA__

  @@ alertassets.js
  alert("Hello World!");

  @@ alertassets.html.ep
  %= javascript "/alertassets.js"

=head1 ADVANCED

Less commonly used and more powerful features.

=head2 Rendering static files

If automatic rendering of static files is not enough, you can also render them
manually from your C<DATA> sections and C<public> directories with
L<Mojolicious::Controller/"render_static">.

  $self->res->headers->content_disposition('attachment; filename=bar.png;');
  $self->render_static('foo/bar.png');

=head2 Custom responses

For entirely custom responses to, for example, stream content directly from
files, you can use L<Mojolicious::Controller/"rendered"> to tell the renderer
that a response has been generated.

  $self->res->headers->content_type('text/plain');
  $self->res->content->asset(Mojo::Asset::File->new(path => '/etc/passwd'));
  $self->rendered(200);

=head2 Post-processing dynamic content

While post-processing tasks are generally very easy with the C<after_dispatch>
hook, for content generated by the renderer it is a lot more efficient to use
C<after_render>.

  use Mojolicious::Lite;
  use IO::Compress::Gzip 'gzip';

  hook after_render => sub {
    my ($c, $output, $format) = @_;

    # Check if "gzip => 1" has been set in the stash
    return unless $c->stash->{gzip};

    # Check if user agent accepts GZip compression
    return unless ($c->req->headers->accept_encoding // '') =~ /gzip/i;
    $c->res->headers->append(Vary => 'Accept-Encoding');

    # Compress content with GZip
    $c->res->headers->content_encoding('gzip');
    gzip $output, \my $compressed;
    $$output = $compressed;
  };

  get '/' => {template => 'hello', title => 'Hello', gzip => 1};

  app->start;
  __DATA__

  @@ hello.html.ep
  <!DOCTYPE html>
  <html>
    <head><title><%= title %></title></head>
    <body>Compressed content.</body>
  </html>

=head2 Chunked transfer encoding

For very dynamic content you might not know the response content length in
advance, that's where the C<chunked> transfer encoding and
L<Mojolicious::Controller/"write_chunk"> come in handy. A common use would be
to send the C<head> section of an HTML document to the browser in advance and
speed up preloading of referenced images and stylesheets.

  $self->write_chunk('<html><head><title>Example</title></head>' => sub {
    my $self = shift;
    $self->finish('<body>Example</body></html>');
  });

The optional drain callback ensures that all previous chunks have been
written before processing continues. An empty chunk or call to
L<Mojolicious::Controller/"finish"> marks the end of the stream.

  29
  <html><head><title>Example</title></head>
  1b
  <body>Example</body></html>
  0

Especially in combination with long inactivity timeouts this can be very
useful for Comet (long polling). Due to limitations in some web servers this
might not work perfectly in all deployment environments.

=head2 Encoding

Templates stored in files are expected to be C<UTF-8> by default, but that can
be easily changed with L<Mojolicious::Renderer/"encoding">.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Different encoding
    $self->renderer->encoding('koi8-r');
  }

  1;

All templates from the C<DATA> section are bound to the encoding of the Perl
script.

  use Mojolicious::Lite;

  get '/heart';

  app->start;

  __DATA__
  @@ heart.html.ep
  I ♥ Mojolicious!

=head2 Base64 encoded DATA files

Base64 encoded static files such as images can be easily stored in the C<DATA>
section of your application, similar to templates.

  @@ favicon.ico (base64)
  ...base64 encoded image...

=head2 Inflating DATA templates

Templates stored in files get preferred over files from the C<DATA> section,
this allows you to include a default set of templates in your application that
the user can later customize. The C<inflate> command will write all templates
and static files from the C<DATA> section into actual files in the
C<templates> and C<public> directories.

  $ ./myapp.pl inflate

=head2 Customizing the template syntax

You can easily change the whole template syntax by loading
L<Mojolicious::Plugin::EPRenderer> with a custom configuration.

  use Mojolicious::Lite;

  plugin EPRenderer => {
    name     => 'mustache',
    template => {
      tag_start => '{{',
      tag_end   => '}}'
    }
  };

  get '/:name' => {name => 'Anonymous'} => 'index';

  app->start;
  __DATA__

  @@ index.html.mustache
  Hello {{= $name }}.

L<Mojo::Template> contains the whole list of available options.

=head2 Adding your favorite template system

Maybe you would prefer a different template system than C<ep>, and there is
not already a plugin on CPAN for your favorite one, all you have to do is add
a new C<handler> with L<Mojolicious::Renderer/"add_handler"> when C<register>
is called.

  package Mojolicious::Plugin::MyRenderer;
  use Mojo::Base 'Mojolicious::Plugin';

  sub register {
    my ($self, $app) = @_;

    # Add "mine" handler
    $app->renderer->add_handler(mine => sub {
      my ($renderer, $c, $output, $options) = @_;

      # Check for one-time use inline template
      my $inline = $options->{inline};

      # Check for absolute template path
      my $path = $renderer->template_path($options);

      # Check for appropriate template in DATA section
      my $data = $renderer->get_data_template($options);

      # This part is up to you and your template system :)
      ...

      # Just die if an error occurs
      die 'Something went wrong';

      # Or pass the rendered result back to the renderer
      $$output = 'Hello World!';

      # And return true if something has been rendered or false otherwise
      return 1;
    });
  }

  1;

Since most template systems don't support templates in the C<DATA> section,
the renderer provides methods to help you with that.

  use Mojolicious::Lite;

  plugin 'MyRenderer';

  get '/' => 'index';

  app->start;
  __DATA__

  @@ index.html.mine
  ...

=head2 Adding a handler to generate binary data

By default the renderer assumes that every C<handler> generates characters
that need to be automatically encoded, but this can be be easily disabled if
you're generating bytes instead.

  use Mojolicious::Lite;
  use Mango::BSON ':bson';

  # Add "bson" handler
  app->renderer->add_handler(bson => sub {
    my ($renderer, $c, $output, $options) = @_;

    # Disable automatic encoding
    delete $options->{encoding};

    # Encode BSON data from stash value
    $$output = bson_encode delete $c->stash->{bson};

    return 1;
  });

  get '/' => {bson => {i => '♥ mojolicious'}, handler => 'bson'};

  app->start;

=head1 MORE

You can continue with L<Mojolicious::Guides> now or take a look at the
L<Mojolicious wiki|http://github.com/kraih/mojo/wiki>, which contains a lot
more documentation and examples by many different authors.

=head1 SUPPORT

If you have any questions the documentation might not yet answer, don't
hesitate to ask on the
L<mailing-list|http://groups.google.com/group/mojolicious> or the official IRC
channel C<#mojo> on C<irc.perl.org>.

=cut