.\" Automatically generated by Pod::Man 4.07 (Pod::Simple 3.32)
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.if !\nF .nr F 0
.if \nF>0 \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
.\}
.\" ========================================================================
.\"
.IX Title "Mojolicious::Guides::Rendering 3pm"
.TH Mojolicious::Guides::Rendering 3pm "2017-01-24" "perl v5.24.1" "User Contributed Perl Documentation"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.if n .ad l
.nh
.SH "NAME"
Mojolicious::Guides::Rendering \- Rendering content
.SH "OVERVIEW"
.IX Header "OVERVIEW"
This document explains content generation with the Mojolicious renderer.
.SH "CONCEPTS"
.IX Header "CONCEPTS"
Essentials every Mojolicious developer should know.
.SS "Renderer"
.IX Subsection "Renderer"
The renderer is a tiny black box turning stash data into actual responses
utilizing multiple template systems and data encoding modules.
.PP
.Vb 3
\& {text => \*(AqHello.\*(Aq} \-> 200 OK, text/html, \*(AqHello.\*(Aq
\& {json => {x => 3}} \-> 200 OK, application/json, \*(Aq{"x":3}\*(Aq
\& {text => \*(AqOops.\*(Aq, status => \*(Aq410\*(Aq} \-> 410 Gone, text/html, \*(AqOops.\*(Aq
.Ve
.PP
Templates can be automatically detected if enough information is provided by
the developer or routes. Template names are expected to follow the
\&\f(CW\*(C`template.format.handler\*(C'\fR scheme, with \f(CW\*(C`template\*(C'\fR defaulting to
\&\f(CW\*(C`controller/action\*(C'\fR or the route name, \f(CW\*(C`format\*(C'\fR defaulting to \f(CW\*(C`html\*(C'\fR and
\&\f(CW\*(C`handler\*(C'\fR to \f(CW\*(C`ep\*(C'\fR.
.PP
.Vb 3
\& {controller => \*(Aqusers\*(Aq, action => \*(Aqlist\*(Aq} \-> \*(Aqusers/list.html.ep\*(Aq
\& {template => \*(Aqfoo\*(Aq, format => \*(Aqtxt\*(Aq} \-> \*(Aqfoo.txt.ep\*(Aq
\& {template => \*(Aqfoo\*(Aq, handler => \*(Aqepl\*(Aq} \-> \*(Aqfoo.html.epl\*(Aq
.Ve
.PP
The \f(CW\*(C`controller\*(C'\fR value gets converted from \f(CW\*(C`CamelCase\*(C'\fR to \f(CW\*(C`snake_case\*(C'\fR using
\&\*(L"decamelize\*(R" in Mojo::Util and \f(CW\*(C`\-\*(C'\fR characters replaced with \f(CW\*(C`/\*(C'\fR.
.PP
.Vb 2
\& {controller => \*(AqMy::Users\*(Aq, action => \*(Aqadd\*(Aq} \-> \*(Aqmy/users/add.html.ep\*(Aq
\& {controller => \*(Aqmy\-users\*(Aq, action => \*(Aqshow\*(Aq} \-> \*(Aqmy/users/show.html.ep\*(Aq
.Ve
.PP
All templates should be in the \f(CW\*(C`templates\*(C'\fR directories of the application,
which can be customized with \*(L"paths\*(R" in Mojolicious::Renderer, or one of the
the \f(CW\*(C`DATA\*(C'\fR sections from \*(L"classes\*(R" in Mojolicious::Renderer.
.PP
.Vb 1
\& _\|_DATA_\|_
\&
\& @@ time.html.ep
\& % use Time::Piece;
\& % my $now = localtime;
\&
\&
\&
Time
\& The time is <%= $now\->hms %>.
\&
\&
\& @@ hello.txt.ep
\& ...
.Ve
.PP
The renderer can be easily extended to support additional template systems with
plugins, but more about that later.
.SS "Embedded Perl"
.IX Subsection "Embedded Perl"
Mojolicious includes a minimalistic but very powerful template system out of
the box called Embedded Perl or \f(CW\*(C`ep\*(C'\fR for short. It is based on
Mojo::Template and allows the embedding of Perl code right into actual
content using a small set of special tags and line start characters. For all
templates strict, warnings, utf8 and Perl 5.10 features are
automatically enabled.
.PP
.Vb 10
\& <% 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 =%>" (explained later)
\& %= Perl expression line, treated as "<%= line %>"
\& %== Perl expression line, treated as "<%== line %>"
\& %# Comment line, useful for debugging
\& %% Replaced with "%", useful for generating templates
.Ve
.PP
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.
.PP
.Vb 8
\& <% my $i = 10; %>
\&
\& <% for my $j (1 .. $i) { %>
\&
\& <%= $j %>
\&
\& <% } %>
\&
\&
\& % my $i = 10;
\&
\& % for my $j (1 .. $i) {
\&
\& %= $j
\&
\& % }
\&
.Ve
.PP
Aside from differences in whitespace handling, both examples generate similar
Perl code, a naive translation could look like this.
.PP
.Vb 10
\& my $output = \*(Aq\*(Aq;
\& my $i = 10;
\& $output .= \*(Aq
\*(Aq;
\& for my $j (1 .. $i) {
\& $output .= \*(Aq
\*(Aq;
\& return $output;
.Ve
.PP
An additional equal sign can be used to disable escaping of the characters
\&\f(CW\*(C`<\*(C'\fR, \f(CW\*(C`>\*(C'\fR, \f(CW\*(C`&\*(C'\fR, \f(CW\*(C`\*(Aq\*(C'\fR and \f(CW\*(C`"\*(C'\fR in results from Perl expressions, which
is the default to prevent \s-1XSS\s0 attacks against your application.
.PP
.Vb 2
\& <%= \*(AqI ♥ Mojolicious!\*(Aq %>
\& <%== \*(Aq
I ♥ Mojolicious!
\*(Aq %>
.Ve
.PP
Only Mojo::ByteStream objects are excluded from automatic escaping.
.PP
.Vb 1
\& <%= b(\*(Aq
I ♥ Mojolicious!
\*(Aq) %>
.Ve
.PP
Whitespace characters around tags can be trimmed by adding an additional equal
sign to the end of a tag.
.PP
.Vb 3
\& <% for (1 .. 3) { %>
\& <%= \*(AqTrim all whitespace characters around this expression\*(Aq =%>
\& <% } %>
.Ve
.PP
Newline characters can be escaped with a backslash.
.PP
.Vb 2
\& This is <%= 1 + 1 %> a\e
\& single line
.Ve
.PP
And a backslash in front of a newline character can be escaped with another
backslash.
.PP
.Vb 3
\& This will <%= 1 + 1 %> result\e\e
\& in multiple\e\e
\& lines
.Ve
.PP
A newline character gets appended automatically to every template, unless the
last character is a backslash. And empty lines at the end of a template are
ignored.
.PP
.Vb 1
\& There is <%= 1 + 1 %> no newline at the end here\e
.Ve
.PP
At the beginning of the template, stash values that don't have invalid
characters in their name get automatically initialized as normal variables, and
the controller object as both \f(CW$self\fR and \f(CW$c\fR.
.PP
.Vb 1
\& $c\->stash(name => \*(Aqtester\*(Aq);
\&
\& Hello <%= $name %> from <%= $c\->tx\->remote_address %>.
.Ve
.PP
A prefix like \f(CW\*(C`myapp.*\*(C'\fR is commonly used for stash values that you don't want
to expose in templates.
.PP
.Vb 1
\& $c\->stash(\*(Aqmyapp.name\*(Aq => \*(Aqtester\*(Aq);
.Ve
.PP
There are also many helper functions available, but more about that later.
.PP
.Vb 1
\& <%= dumper {foo => \*(Aqbar\*(Aq} %>
.Ve
.SH "BASICS"
.IX Header "BASICS"
Most commonly used features every Mojolicious developer should know about.
.SS "Automatic rendering"
.IX Subsection "Automatic rendering"
The renderer can be manually started by calling the method
\&\*(L"render\*(R" in Mojolicious::Controller, 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.
.PP
.Vb 1
\& $c\->render;
.Ve
.PP
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"controller_class\*(R" in Mojolicious.
.PP
.Vb 1
\& $c\->render_later;
.Ve
.PP
You can also disable automatic rendering with the method
\&\*(L"render_later\*(R" in Mojolicious::Controller, which can be very useful to delay
rendering when a non-blocking operation has to be performed first.
.SS "Rendering templates"
.IX Subsection "Rendering templates"
The renderer will always try to detect the right template, but you can also use
the \f(CW\*(C`template\*(C'\fR 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.
.PP
.Vb 2
\& # foo/bar/baz.*.*
\& $c\->render(template => \*(Aqfoo/bar/baz\*(Aq);
.Ve
.PP
Choosing a specific \f(CW\*(C`format\*(C'\fR and \f(CW\*(C`handler\*(C'\fR is just as easy.
.PP
.Vb 2
\& # foo/bar/baz.txt.epl
\& $c\->render(template => \*(Aqfoo/bar/baz\*(Aq, format => \*(Aqtxt\*(Aq, handler => \*(Aqepl\*(Aq);
.Ve
.PP
Because rendering a specific template is the most common task it also has a
shortcut.
.PP
.Vb 1
\& $c\->render(\*(Aqfoo/bar/baz\*(Aq);
.Ve
.PP
If you're not sure in advance if a template actually exists, you can also use
the method \*(L"render_maybe\*(R" in Mojolicious::Controller to try multiple
alternatives.
.PP
.Vb 1
\& $c\->render_maybe(\*(Aqlocalized/baz\*(Aq) or $c\->render(\*(Aqfoo/bar/baz\*(Aq);
.Ve
.SS "Rendering to strings"
.IX Subsection "Rendering to strings"
Sometimes you might want to use the rendered result directly instead of
generating a response, for example, to send emails, this can be done with
\&\*(L"render_to_string\*(R" in Mojolicious::Controller.
.PP
.Vb 1
\& my $html = $c\->render_to_string(\*(Aqmail\*(Aq);
.Ve
.PP
No encoding will be performed, making it easy to reuse the result in other
templates or to generate binary data.
.PP
.Vb 2
\& my $pdf = $c\->render_to_string(\*(Aqinvoice\*(Aq, format => \*(Aqpdf\*(Aq);
\& $c\->render(data => $pdf, format => \*(Aqpdf\*(Aq);
.Ve
.PP
All arguments passed will get localized automatically and are only available
during this render operation.
.SS "Template variants"
.IX Subsection "Template variants"
To make your application look great on many different devices you can also use
the \f(CW\*(C`variant\*(C'\fR stash value to choose between different variants of your
templates.
.PP
.Vb 3
\& # foo/bar/baz.html+phone.ep
\& # foo/bar/baz.html.ep
\& $c\->render(\*(Aqfoo/bar/baz\*(Aq, variant => \*(Aqphone\*(Aq);
.Ve
.PP
This can be done very liberally since it only applies when a template with the
correct name actually exists and falls back to the generic one otherwise.
.SS "Rendering inline templates"
.IX Subsection "Rendering inline templates"
Some renderers such as \f(CW\*(C`ep\*(C'\fR allow templates to be passed \f(CW\*(C`inline\*(C'\fR.
.PP
.Vb 1
\& $c\->render(inline => \*(AqThe result is <%= 1 + 1 %>.\*(Aq);
.Ve
.PP
Since auto-detection depends on a path you might have to supply a \f(CW\*(C`handler\*(C'\fR
too.
.PP
.Vb 1
\& $c\->render(inline => "<%= shift\->param(\*(Aqfoo\*(Aq) %>", handler => \*(Aqepl\*(Aq);
.Ve
.SS "Rendering text"
.IX Subsection "Rendering text"
Characters can be rendered to bytes with the \f(CW\*(C`text\*(C'\fR stash value, the given
content will be automatically encoded with \*(L"encoding\*(R" in Mojolicious::Renderer.
.PP
.Vb 1
\& $c\->render(text => \*(AqI ♥ Mojolicious!\*(Aq);
.Ve
.SS "Rendering data"
.IX Subsection "Rendering data"
Bytes can be rendered with the \f(CW\*(C`data\*(C'\fR stash value, no encoding will be
performed.
.PP
.Vb 1
\& $c\->render(data => $bytes);
.Ve
.SS "Rendering \s-1JSON\s0"
.IX Subsection "Rendering JSON"
The \f(CW\*(C`json\*(C'\fR stash value allows you to pass Perl data structures to the renderer
which get directly encoded to \s-1JSON\s0 with Mojo::JSON.
.PP
.Vb 1
\& $c\->render(json => {foo => [1, \*(Aqtest\*(Aq, 3]});
.Ve
.SS "Status code"
.IX Subsection "Status code"
Response status codes can be changed with the \f(CW\*(C`status\*(C'\fR stash value.
.PP
.Vb 1
\& $c\->render(text => \*(AqOops.\*(Aq, status => 500);
.Ve
.SS "Content type"
.IX Subsection "Content type"
The \f(CW\*(C`Content\-Type\*(C'\fR header of the response is actually based on the \s-1MIME\s0 type
mapping of the \f(CW\*(C`format\*(C'\fR stash value.
.PP
.Vb 2
\& # Content\-Type: text/plain
\& $c\->render(text => \*(AqHello.\*(Aq, format => \*(Aqtxt\*(Aq);
\&
\& # Content\-Type: image/png
\& $c\->render(data => $bytes, format => \*(Aqpng\*(Aq);
.Ve
.PP
These mappings can be easily extended or changed with \*(L"types\*(R" in Mojolicious.
.PP
.Vb 2
\& # Add new MIME type
\& $app\->types\->type(md => \*(Aqtext/markdown\*(Aq);
.Ve
.SS "Stash data"
.IX Subsection "Stash data"
Any of the native Perl data types can be passed to templates as references
through the \*(L"stash\*(R" in Mojolicious::Controller.
.PP
.Vb 3
\& $c\->stash(description => \*(Aqweb framework\*(Aq);
\& $c\->stash(frameworks => [\*(AqCatalyst\*(Aq, \*(AqMojolicious\*(Aq]);
\& $c\->stash(spinoffs => {minion => \*(Aqjob queue\*(Aq});
\&
\& %= $description
\& %= $frameworks\->[1]
\& %= $spinoffs\->{minion}
.Ve
.PP
Since everything is just Perl normal control structures just work.
.PP
.Vb 3
\& % for my $framework (@$frameworks) {
\& <%= $framework %> is a <%= $description %>.
\& % }
\&
\& % if (my $description = $spinoffs\->{minion}) {
\& Minion is a <%= $description %>.
\& % }
.Ve
.PP
For templates that might get rendered in different ways and where you're not
sure if a stash value will actually be set, you can just use the helper
\&\*(L"stash\*(R" in Mojolicious::Plugin::DefaultHelpers.
.PP
.Vb 3
\& % if (my $spinoffs = stash \*(Aqspinoffs\*(Aq) {
\& Minion is a <%= $spinoffs\->{minion} %>.
\& % }
.Ve
.PP
Just be aware that too many optional stash values will make templates less
cacheable, which can reduce performance. So passing an \f(CW\*(C`undef\*(C'\fR value to the
stash, instead of making it optional, is always preferable.
.SS "Helpers"
.IX Subsection "Helpers"
Helpers are little functions you can use in templates as well as application
and controller code.
.PP
.Vb 2
\& # Template
\& %= dumper [1, 2, 3]
\&
\& # Application
\& my $serialized = $app\->dumper([1, 2, 3]);
\&
\& # Controller
\& my $serialized = $c\->dumper([1, 2, 3]);
.Ve
.PP
We differentiate between default helpers, which are more general purpose like
\&\*(L"dumper\*(R" in Mojolicious::Plugin::DefaultHelpers, and tag helpers like
\&\*(L"link_to\*(R" in Mojolicious::Plugin::TagHelpers, which are template specific and
mostly used to generate \s-1HTML\s0 tags.
.PP
.Vb 1
\& %= link_to Mojolicious => \*(Aqhttp://mojolicious.org\*(Aq
.Ve
.PP
In controllers you can also use the method \*(L"helpers\*(R" in Mojolicious::Controller
to fully qualify helper calls and ensure that they don't conflict with existing
methods you may already have.
.PP
.Vb 1
\& my $serialized = $c\->helpers\->dumper([1, 2, 3]);
.Ve
.PP
A list of all built-in helpers can be found in
Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.
.SS "Content negotiation"
.IX Subsection "Content negotiation"
For resources with different representations and that require truly RESTful
content negotiation you can also use \*(L"respond_to\*(R" in Mojolicious::Controller
instead of \*(L"render\*(R" in Mojolicious::Controller.
.PP
.Vb 10
\& # /hello (Accept: application/json) \-> "json"
\& # /hello (Accept: application/xml) \-> "xml"
\& # /hello.json \-> "json"
\& # /hello.xml \-> "xml"
\& # /hello?format=json \-> "json"
\& # /hello?format=xml \-> "xml"
\& $c\->respond_to(
\& json => {json => {hello => \*(Aqworld\*(Aq}},
\& xml => {text => \*(Aqworld\*(Aq}
\& );
.Ve
.PP
The best possible representation will be automatically selected from the
\&\f(CW\*(C`Accept\*(C'\fR request header, \f(CW\*(C`format\*(C'\fR stash value or \f(CW\*(C`format\*(C'\fR \f(CW\*(C`GET\*(C'\fR/\f(CW\*(C`POST\*(C'\fR
parameter and stored in the \f(CW\*(C`format\*(C'\fR stash value. To change \s-1MIME\s0 type mappings
for the \f(CW\*(C`Accept\*(C'\fR request header or the \f(CW\*(C`Content\-Type\*(C'\fR response header you can
use \*(L"types\*(R" in Mojolicious.
.PP
.Vb 7
\& $c\->respond_to(
\& json => {json => {hello => \*(Aqworld\*(Aq}},
\& html => sub {
\& $c\->content_for(head => \*(Aq\*(Aq);
\& $c\->render(template => \*(Aqhello\*(Aq, message => \*(Aqworld\*(Aq)
\& }
\& );
.Ve
.PP
Callbacks can be used for representations that are too complex to fit into a
single render call.
.PP
.Vb 10
\& # /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"
\& $c\->respond_to(
\& json => {json => {hello => \*(Aqworld\*(Aq}},
\& html => {template => \*(Aqhello\*(Aq, message => \*(Aqworld\*(Aq},
\& any => {text => \*(Aq\*(Aq, status => 204}
\& );
.Ve
.PP
And if no viable representation could be found, the \f(CW\*(C`any\*(C'\fR fallback will be
used or an empty \f(CW204\fR response rendered automatically.
.PP
.Vb 10
\& # /hello \-> "html"
\& # /hello (Accept: text/html) \-> "html"
\& # /hello (Accept: text/xml) \-> "xml"
\& # /hello (Accept: text/plain) \-> undef
\& # /hello.html \-> "html"
\& # /hello.xml \-> "xml"
\& # /hello.txt \-> undef
\& # /hello?format=html \-> "html"
\& # /hello?format=xml \-> "xml"
\& # /hello?format=txt \-> undef
\& if (my $format = $c\->accepts(\*(Aqhtml\*(Aq, \*(Aqxml\*(Aq)) {
\& ...
\& }
.Ve
.PP
For even more advanced negotiation logic you can also use the helper
\&\*(L"accepts\*(R" in Mojolicious::Plugin::DefaultHelpers.
.ie n .SS "Rendering ""exception"" and ""not_found"" pages"
.el .SS "Rendering \f(CWexception\fP and \f(CWnot_found\fP pages"
.IX Subsection "Rendering exception and not_found pages"
By now you've probably already encountered the built-in \f(CW404\fR (Not Found) and
\&\f(CW500\fR (Server Error) pages, that get rendered automatically when you make a
mistake. Those are fallbacks for when your own exception handling fails, which
can be especially helpful during development. You can also render them manually
with the helpers \*(L"reply\->exception\*(R" in Mojolicious::Plugin::DefaultHelpers
and \*(L"reply\->not_found\*(R" in Mojolicious::Plugin::DefaultHelpers.
.PP
.Vb 2
\& use Mojolicious::Lite;
\& use Scalar::Util \*(Aqlooks_like_number\*(Aq;
\&
\& get \*(Aq/divide/:dividend/by/:divisor\*(Aq => sub {
\& my $c = shift;
\&
\& my $dividend = $c\->param(\*(Aqdividend\*(Aq);
\& my $divisor = $c\->param(\*(Aqdivisor\*(Aq);
\&
\& # 404
\& return $c\->reply\->not_found
\& unless looks_like_number $dividend && looks_like_number $divisor;
\&
\& # 500
\& return $c\->reply\->exception(\*(AqDivision by zero!\*(Aq) if $divisor == 0;
\&
\& # 200
\& $c\->render(text => $dividend / $divisor);
\& };
\&
\& app\->start;
.Ve
.PP
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 \f(CW\*(C`exception.$mode.$format.*\*(C'\fR
or \f(CW\*(C`not_found.$mode.$format.*\*(C'\fR before falling back to the built-in default
templates.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/dies\*(Aq => sub { die \*(AqIntentional error\*(Aq };
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ exception.production.html.ep
\&
\&
\& Server error
\&
\&
Exception
\&
<%= $exception\->message %>
\&
Stash
\&
<%= dumper $snapshot %>
\&
\&
.Ve
.PP
The hook \*(L"before_render\*(R" in Mojolicious makes even more advanced customizations
possible by allowing you to intercept and modify the arguments passed to the
renderer.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& hook before_render => sub {
\& my ($c, $args) = @_;
\&
\& # Make sure we are rendering the exception template
\& return unless my $template = $args\->{template};
\& return unless $template eq \*(Aqexception\*(Aq;
\&
\& # Switch to JSON rendering if content negotiation allows it
\& $args\->{json} = {exception => $args\->{exception}} if $c\->accepts(\*(Aqjson\*(Aq);
\& };
\&
\& get \*(Aq/\*(Aq => sub { die "This sho...ALL GLORY TO THE HYPNOTOAD!\en" };
\&
\& app\->start;
.Ve
.SS "Layouts"
.IX Subsection "Layouts"
Most of the time when using \f(CW\*(C`ep\*(C'\fR templates you will want to wrap your
generated content in an \s-1HTML\s0 skeleton, thanks to layouts that's absolutely
trivial.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => {template => \*(Aqfoo/bar\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ foo/bar.html.ep
\& % layout \*(Aqmylayout\*(Aq;
\& Hello World!
\&
\& @@ layouts/mylayout.html.ep
\&
\&
\& MyApp
\& <%= content %>
\&
.Ve
.PP
You just select the right layout template with the helper
\&\*(L"layout\*(R" in Mojolicious::Plugin::DefaultHelpers and place the result of the
current template with the helper
\&\*(L"content\*(R" in Mojolicious::Plugin::DefaultHelpers. You can also pass along
normal stash values to the \f(CW\*(C`layout\*(C'\fR helper.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => {template => \*(Aqfoo/bar\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ foo/bar.html.ep
\& % layout \*(Aqmylayout\*(Aq, title => \*(AqHi there\*(Aq;
\& Hello World!
\&
\& @@ layouts/mylayout.html.ep
\&
\&
\& <%= $title %>
\& <%= content %>
\&
.Ve
.PP
Instead of the \f(CW\*(C`layout\*(C'\fR helper you could also just use the \f(CW\*(C`layout\*(C'\fR stash
value, or call \*(L"render\*(R" in Mojolicious::Controller with the \f(CW\*(C`layout\*(C'\fR argument.
.PP
.Vb 1
\& $c\->render(template => \*(Aqmytemplate\*(Aq, layout => \*(Aqmylayout\*(Aq);
.Ve
.PP
To set a \f(CW\*(C`layout\*(C'\fR stash value application-wide you can use
\&\*(L"defaults\*(R" in Mojolicious.
.PP
.Vb 1
\& $app\->defaults(layout => \*(Aqmylayout\*(Aq);
.Ve
.PP
Layouts can also be used with \*(L"render_to_string\*(R" in Mojolicious::Controller,
but the \f(CW\*(C`layout\*(C'\fR value needs to be passed as a render argument (not a stash
value).
.PP
.Vb 1
\& my $html = $c\->render_to_string(\*(Aqreminder\*(Aq, layout => \*(Aqmail\*(Aq);
.Ve
.SS "Partial templates"
.IX Subsection "Partial templates"
You can break up bigger templates into smaller, more manageable chunks. These
partial templates can also be shared with other templates. Just use the helper
\&\*(L"include\*(R" in Mojolicious::Plugin::DefaultHelpers to include one template into
another.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => {template => \*(Aqfoo/bar\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ foo/bar.html.ep
\&
\&
\& %= include \*(Aqheader\*(Aq, title => \*(AqHowdy\*(Aq
\& Bar
\&
\&
\& @@ header.html.ep
\& <%= $title %>
.Ve
.SS "Reusable template blocks"
.IX Subsection "Reusable template blocks"
It's never fun to repeat yourself, that's why you can build reusable template
blocks in \f(CW\*(C`ep\*(C'\fR that work very similar to normal Perl functions, with the
\&\f(CW\*(C`begin\*(C'\fR and \f(CW\*(C`end\*(C'\fR keywords. Just be aware that both keywords are part of the
surrounding tag and not actual Perl code, so there can only be whitespace after
\&\f(CW\*(C`begin\*(C'\fR and before \f(CW\*(C`end\*(C'\fR.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => \*(Aqwelcome\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ welcome.html.ep
\& <% my $block = begin %>
\& % my $name = shift;
\& Hello <%= $name %>.
\& <% end %>
\& <%= $block\->(\*(AqWolfgang\*(Aq) %>
\& <%= $block\->(\*(AqBaerbel\*(Aq) %>
.Ve
.PP
A naive translation of the template to Perl code could look like this.
.PP
.Vb 12
\& my $output = \*(Aq\*(Aq;
\& my $block = sub {
\& my $name = shift;
\& my $output = \*(Aq\*(Aq;
\& $output .= \*(AqHello \*(Aq;
\& $output .= xml_escape scalar + $name;
\& $output .= \*(Aq.\*(Aq;
\& return Mojo::ByteStream\->new($output);
\& };
\& $output .= xml_escape scalar + $block\->(\*(AqWolfgang\*(Aq);
\& $output .= xml_escape scalar + $block\->(\*(AqBaerbel\*(Aq);
\& return $output;
.Ve
.PP
While template blocks cannot be shared between templates, they are most
commonly used to pass parts of a template to helpers.
.SS "Adding helpers"
.IX Subsection "Adding helpers"
You should always try to keep your actions small and reuse as much code as
possible. Helpers make this very easy, they get passed the current controller
object as first argument, and you can use them to do pretty much anything an
action could do.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& helper debug => sub {
\& my ($c, $str) = @_;
\& $c\->app\->log\->debug($str);
\& };
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\& $c\->debug(\*(AqHello from an action!\*(Aq);
\& } => \*(Aqindex\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ index.html.ep
\& % debug \*(AqHello from a template!\*(Aq;
.Ve
.PP
Helpers can also accept template blocks as last argument, this for example,
allows very pleasant to use tag helpers and filters. Wrapping the helper result
into a Mojo::ByteStream object can prevent accidental double escaping.
.PP
.Vb 2
\& use Mojolicious::Lite;
\& use Mojo::ByteStream;
\&
\& helper trim_newline => sub {
\& my ($c, $block) = @_;
\& my $result = $block\->();
\& $result =~ s/\en//g;
\& return Mojo::ByteStream\->new($result);
\& };
\&
\& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ index.html.ep
\& %= trim_newline begin
\& Some text.
\& %= 1 + 1
\& More text.
\& % end
.Ve
.PP
Similar to stash values, you can use a prefix like \f(CW\*(C`myapp.*\*(C'\fR to keep helpers
from getting exposed in templates as functions, and to organize them into
namespaces as your application grows. Every prefix automatically becomes a
helper that returns a proxy object containing the current controller object and
on which you can call the nested helpers.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& helper \*(Aqcache_control.no_caching\*(Aq => sub {
\& my $c = shift;
\& $c\->res\->headers\->cache_control(\*(Aqprivate, max\-age=0, no\-cache\*(Aq);
\& };
\&
\& helper \*(Aqcache_control.five_minutes\*(Aq => sub {
\& my $c = shift;
\& $c\->res\->headers\->cache_control(\*(Aqpublic, max\-age=300\*(Aq);
\& };
\&
\& get \*(Aq/news\*(Aq => sub {
\& my $c = shift;
\& $c\->cache_control\->no_caching;
\& $c\->render(text => \*(AqAlways up to date.\*(Aq);
\& };
\&
\& get \*(Aq/some_older_story\*(Aq => sub {
\& my $c = shift;
\& $c\->cache_control\->five_minutes;
\& $c\->render(text => \*(AqThis one can be cached for a bit.\*(Aq);
\& };
\&
\& app\->start;
.Ve
.PP
While helpers can also be redefined, this should only be done very carefully to
avoid conflicts.
.SS "Content blocks"
.IX Subsection "Content blocks"
The helper \*(L"content_for\*(R" in Mojolicious::Plugin::DefaultHelpers allows you to
pass whole blocks of content from one template to another. This can be very
useful when your layout has distinct sections, such as sidebars, where content
should be inserted by the template.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => \*(Aqfoo\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ foo.html.ep
\& % layout \*(Aqmylayout\*(Aq;
\& % content_for header => begin
\&
\& % end
\&
Hello World!
\& % content_for header => begin
\&
\& % end
\&
\& @@ layouts/mylayout.html.ep
\&
\&
\& <%= content \*(Aqheader\*(Aq %>
\& <%= content %>
\&
.Ve
.SS "Forms"
.IX Subsection "Forms"
To build \s-1HTML\s0 forms more efficiently you can use tag helpers like
\&\*(L"form_for\*(R" in Mojolicious::Plugin::TagHelpers, which can automatically select a
request method for you if a route name is provided. And since most browsers
only allow forms to be submitted with \f(CW\*(C`GET\*(C'\fR and \f(CW\*(C`POST\*(C'\fR, but not request
methods like \f(CW\*(C`PUT\*(C'\fR or \f(CW\*(C`DELETE\*(C'\fR, they are spoofed with an \f(CW\*(C`_method\*(C'\fR query
parameter.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => \*(Aqform\*(Aq;
\&
\& # PUT /nothing
\& # POST /nothing?_method=PUT
\& put \*(Aq/nothing\*(Aq => sub {
\& my $c = shift;
\&
\& # Prevent double form submission with redirect
\& my $value = $c\->param(\*(Aqwhatever\*(Aq);
\& $c\->flash(confirmation => "We did nothing with your value ($value).");
\& $c\->redirect_to(\*(Aqform\*(Aq);
\& };
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ form.html.ep
\&
\&
\&
\& % if (my $confirmation = flash \*(Aqconfirmation\*(Aq) {
\&
<%= $confirmation %>
\& % }
\& %= form_for nothing => begin
\& %= text_field whatever => \*(AqI ♥ Mojolicious!\*(Aq
\& %= submit_button
\& % end
\&
\&
.Ve
.PP
The methods \*(L"flash\*(R" in Mojolicious::Controller and
\&\*(L"redirect_to\*(R" in Mojolicious::Controller are often used together to prevent
double form submission, allowing users to receive a confirmation message that
will vanish if they decide to reload the page they've been redirected to.
.SS "Form validation"
.IX Subsection "Form validation"
You can use \*(L"validation\*(R" in Mojolicious::Controller to validate \f(CW\*(C`GET\*(C'\fR and
\&\f(CW\*(C`POST\*(C'\fR 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"is_valid\*(R" in Mojolicious::Validator::Validation.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\&
\& # Check if parameters have been submitted
\& my $validation = $c\->validation;
\& return $c\->render unless $validation\->has_data;
\&
\& # Validate parameters ("pass_again" depends on "pass")
\& $validation\->required(\*(Aquser\*(Aq)\->size(1, 20)\->like(qr/^[e\-t]+$/);
\& $validation\->required(\*(Aqpass_again\*(Aq)\->equal_to(\*(Aqpass\*(Aq)
\& if $validation\->optional(\*(Aqpass\*(Aq)\->size(7, 500)\->is_valid;
\&
\& # Render confirmation if validation was successful
\& $c\->render(\*(Aqthanks\*(Aq) unless $validation\->has_error;
\& } => \*(Aqindex\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ index.html.ep
\&
\&
\&
\&
\&
\&
\& %= form_for index => begin
\& %= label_for user => \*(AqUsername (required, 1\-20 characters, only e\-t)\*(Aq
\&
\& %= text_field \*(Aquser\*(Aq, id => \*(Aquser\*(Aq
\& %= submit_button
\&
\& %= label_for pass => \*(AqPassword (optional, 7\-500 characters)\*(Aq
\&
\& %= password_field \*(Aqpass\*(Aq, id => \*(Aqpass\*(Aq
\&
\& %= label_for pass_again => \*(AqPassword again (equal to the value above)\*(Aq
\&
\& %= password_field \*(Aqpass_again\*(Aq, id => \*(Aqpass_again\*(Aq
\& % end
\&
\&
\&
\& @@ thanks.html.ep
\&
\& Thank you <%= validation\->param(\*(Aquser\*(Aq) %>.
.Ve
.PP
Form elements generated with tag helpers from
Mojolicious::Plugin::TagHelpers will automatically remember their previous
values and add the class \f(CW\*(C`field\-with\-error\*(C'\fR for fields that failed validation
to make styling with \s-1CSS\s0 easier.
.PP
.Vb 4
\&
\&
.Ve
.PP
For a full list of available checks see also
\&\*(L"\s-1CHECKS\*(R"\s0 in Mojolicious::Validator.
.SS "Adding form validation checks"
.IX Subsection "Adding form validation checks"
Validation checks can be registered with \*(L"add_check\*(R" in Mojolicious::Validator
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"error\*(R" in Mojolicious::Validator::Validation.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& # Add "range" check
\& app\->validator\->add_check(range => sub {
\& my ($validation, $name, $value, $min, $max) = @_;
\& return $value < $min || $value > $max;
\& });
\&
\& get \*(Aq/\*(Aq => \*(Aqform\*(Aq;
\&
\& post \*(Aq/test\*(Aq => sub {
\& my $c = shift;
\&
\& # Validate parameters with custom check
\& my $validation = $c\->validation;
\& $validation\->required(\*(Aqnumber\*(Aq)\->range(3, 23);
\&
\& # Render form again if validation failed
\& return $c\->render(\*(Aqform\*(Aq) if $validation\->has_error;
\&
\& # Prevent double form submission with redirect
\& $c\->flash(number => $validation\->param(\*(Aqnumber\*(Aq));
\& $c\->redirect_to(\*(Aqform\*(Aq);
\& };
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ form.html.ep
\&
\&
\&
\& % if (my $number = flash \*(Aqnumber\*(Aq) {
\&
Thanks, the number <%= $number %> was valid.
\& % }
\& %= form_for test => begin
\& % if (my $err = validation\->error(\*(Aqnumber\*(Aq)) {
\&
\& %= \*(AqValue is required.\*(Aq if $err\->[0] eq \*(Aqrequired\*(Aq
\& %= \*(AqValue needs to be between 3 and 23.\*(Aq if $err\->[0] eq \*(Aqrange\*(Aq
\&
\& % }
\& %= text_field \*(Aqnumber\*(Aq
\& %= submit_button
\& % end
\&
\&
.Ve
.SS "Cross-site request forgery"
.IX Subsection "Cross-site request forgery"
\&\s-1CSRF\s0 is a very common attack on web applications that trick your logged in
users to submit forms they did not intend to send, with something as mundane as
a link. All you have to do, to protect your users from this, is to add an
additional hidden field to your forms with
\&\*(L"csrf_field\*(R" in Mojolicious::Plugin::TagHelpers, and validate it with
\&\*(L"csrf_protect\*(R" in Mojolicious::Validator::Validation.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => {template => \*(Aqtarget\*(Aq};
\&
\& post \*(Aq/\*(Aq => sub {
\& my $c = shift;
\&
\& # Check CSRF token
\& my $validation = $c\->validation;
\& return $c\->render(text => \*(AqBad CSRF token!\*(Aq, status => 403)
\& if $validation\->csrf_protect\->has_error(\*(Aqcsrf_token\*(Aq);
\&
\& my $city = $validation\->required(\*(Aqcity\*(Aq)\->param(\*(Aqcity\*(Aq);
\& $c\->render(text => "Low orbit ion cannon pointed at $city!")
\& unless $validation\->has_error;
\& } => \*(Aqtarget\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ target.html.ep
\&
\&
\&
\& %= form_for target => begin
\& %= csrf_field
\& %= label_for city => \*(AqWhich city to point low orbit ion cannon at?\*(Aq
\& %= text_field \*(Aqcity\*(Aq, id => \*(Aqcity\*(Aq
\& %= submit_button
\& %= end
\&
\&
.Ve
.PP
For Ajax requests and the like, you can also generate a token directly with the
helper \*(L"csrf_token\*(R" in Mojolicious::Plugin::DefaultHelpers, and then pass it
along with the \f(CW\*(C`X\-CSRF\-Token\*(C'\fR request header.
.SH "ADVANCED"
.IX Header "ADVANCED"
Less commonly used and more powerful features.
.SS "Template inheritance"
.IX Subsection "Template inheritance"
Inheritance takes the layout concept above one step further, the helpers
\&\*(L"content\*(R" in Mojolicious::Plugin::DefaultHelpers and
\&\*(L"extends\*(R" in Mojolicious::Plugin::DefaultHelpers allow you to build skeleton
templates with named blocks that child templates can override.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& # first > mylayout
\& get \*(Aq/first\*(Aq => {template => \*(Aqfirst\*(Aq, layout => \*(Aqmylayout\*(Aq};
\&
\& # third > second > first > mylayout
\& get \*(Aq/third\*(Aq => {template => \*(Aqthird\*(Aq, layout => \*(Aqmylayout\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ layouts/mylayout.html.ep
\&
\&
\& Hello
\& <%= content %>
\&
\&
\& @@ first.html.ep
\& %= content header => begin
\& Default header
\& % end
\&
Hello World!
\& %= content footer => begin
\& Default footer
\& % end
\&
\& @@ second.html.ep
\& % extends \*(Aqfirst\*(Aq;
\& % content header => begin
\& New header
\& % end
\&
\& @@ third.html.ep
\& % extends \*(Aqsecond\*(Aq;
\& % content footer => begin
\& New footer
\& % end
.Ve
.PP
This chain could go on and on to allow a very high level of template reuse.
.SS "Serving static files"
.IX Subsection "Serving static files"
Static files are automatically served from the \f(CW\*(C`public\*(C'\fR directories of the
application, which can be customized with \*(L"paths\*(R" in Mojolicious::Static, or one
of the \f(CW\*(C`DATA\*(C'\fR sections from \*(L"classes\*(R" in Mojolicious::Static. And if that's not
enough you can also serve them manually with
\&\*(L"reply\->static\*(R" in Mojolicious::Plugin::DefaultHelpers.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\& $c\->reply\->static(\*(Aqindex.html\*(Aq);
\& };
\&
\& get \*(Aq/some_download\*(Aq => sub {
\& my $c = shift;
\& $c\->res\->headers\->content_disposition(\*(Aqattachment; filename=bar.png;\*(Aq);
\& $c\->reply\->static(\*(Aqfoo/bar.png\*(Aq);
\& };
\&
\& app\->start;
.Ve
.SS "Custom responses"
.IX Subsection "Custom responses"
Most response content, static as well as dynamic, gets served through
Mojo::Asset::File and Mojo::Asset::Memory objects. For somewhat static
content, like cached \s-1JSON\s0 data or temporary files, you can create your own and
use the helper \*(L"reply\->asset\*(R" in Mojolicious::Plugin::DefaultHelpers to
serve them while allowing content negotiation to be performed with \f(CW\*(C`Range\*(C'\fR,
\&\f(CW\*(C`If\-Modified\-Since\*(C'\fR and \f(CW\*(C`If\-None\-Match\*(C'\fR headers.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/leak\*(Aq => sub {
\& my $c = shift;
\& $c\->res\->headers\->content_type(\*(Aqtext/plain\*(Aq);
\& $c\->reply\->asset(Mojo::Asset::File\->new(path => \*(Aq/etc/passwd\*(Aq));
\& };
\&
\& app\->start;
.Ve
.PP
For even more control you can also just skip the helper and use
\&\*(L"rendered\*(R" in Mojolicious::Controller to tell the renderer when you're done
generating a response.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/leak\*(Aq => sub {
\& my $c = shift;
\& $c\->res\->headers\->content_type(\*(Aqtext/plain\*(Aq);
\& $c\->res\->content\->asset(Mojo::Asset::File\->new(path => \*(Aq/etc/passwd\*(Aq));
\& $c\->rendered(200);
\& };
\&
\& app\->start;
.Ve
.SS "Helper plugins"
.IX Subsection "Helper plugins"
Some helpers might be useful enough for you to share them between multiple
applications, plugins make that very simple.
.PP
.Vb 2
\& package Mojolicious::Plugin::DebugHelper;
\& use Mojo::Base \*(AqMojolicious::Plugin\*(Aq;
\&
\& sub register {
\& my ($self, $app) = @_;
\& $app\->helper(debug => sub {
\& my ($c, $str) = @_;
\& $c\->app\->log\->debug($str);
\& });
\& }
\&
\& 1;
.Ve
.PP
The \f(CW\*(C`register\*(C'\fR method will be called when you load the plugin. And to add your
helper to the application, you can use \*(L"helper\*(R" in Mojolicious.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& plugin \*(AqDebugHelper\*(Aq;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\& $c\->debug(\*(AqIt works!\*(Aq);
\& $c\->render(text => \*(AqHello!\*(Aq);
\& };
\&
\& app\->start;
.Ve
.PP
A skeleton for a full \s-1CPAN\s0 compatible plugin distribution can be automatically
generated.
.PP
.Vb 1
\& $ mojo generate plugin DebugHelper
.Ve
.PP
And if you have a \f(CW\*(C`PAUSE\*(C'\fR account (which can be requested at
), you are only a few commands away from releasing it
to \s-1CPAN.\s0
.PP
.Vb 5
\& $ perl Makefile.PL
\& $ make test
\& $ make manifest
\& $ make dist
\& $ mojo cpanify \-u USER \-p PASS Mojolicious\-Plugin\-DebugHelper\-0.01.tar.gz
.Ve
.SS "Bundling assets with plugins"
.IX Subsection "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 \s-1CPAN.\s0
.PP
.Vb 7
\& $ mojo generate plugin AlertAssets
\& $ mkdir Mojolicious\-Plugin\-AlertAssets/lib/Mojolicious/Plugin/AlertAssets
\& $ cd Mojolicious\-Plugin\-AlertAssets/lib/Mojolicious/Plugin/AlertAssets
\& $ mkdir public
\& $ echo \*(Aqalert("Hello World!");\*(Aq > public/alertassets.js
\& $ mkdir templates
\& $ echo \*(Aq%= javascript "/alertassets.js"\*(Aq > templates/alertassets.html.ep
.Ve
.PP
Just give them reasonably unique names, ideally based on the name of your
plugin, and append their respective directories to the list of search paths
when \f(CW\*(C`register\*(C'\fR is called.
.PP
.Vb 2
\& package Mojolicious::Plugin::AlertAssets;
\& use Mojo::Base \*(AqMojolicious::Plugin\*(Aq;
\&
\& use Mojo::File \*(Aqpath\*(Aq;
\&
\& sub register {
\& my ($self, $app) = @_;
\&
\& # Append "templates" and "public" directories
\& my $base = path(_\|_FILE_\|_)\->dirname\->child(\*(AqAlertAssets\*(Aq);
\& push @{$app\->renderer\->paths}, $base\->child(\*(Aqtemplates\*(Aq)\->to_string;
\& push @{$app\->static\->paths}, $base\->child(\*(Aqpublic\*(Aq)\->to_string;
\& }
\&
\& 1;
.Ve
.PP
Both will work just like normal \f(CW\*(C`templates\*(C'\fR and \f(CW\*(C`public\*(C'\fR directories once
you've installed and loaded the plugin, with slightly lower precedence.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& plugin \*(AqAlertAssets\*(Aq;
\&
\& get \*(Aq/alert_me\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ alert_me.html.ep
\&
\&
\&
\& Alert me!
\& %= include \*(Aqalertassets\*(Aq
\&
\& You\*(Aqve been alerted.
\&
.Ve
.PP
And it works just the same for assets bundled in the \f(CW\*(C`DATA\*(C'\fR section of your
plugin.
.PP
.Vb 2
\& package Mojolicious::Plugin::AlertAssets;
\& use Mojo::Base \*(AqMojolicious::Plugin\*(Aq;
\&
\& 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"
.Ve
.SS "Post-processing dynamic content"
.IX Subsection "Post-processing dynamic content"
While post-processing tasks are generally very easy with the hook
\&\*(L"after_dispatch\*(R" in Mojolicious, for content generated by the renderer it is a
lot more efficient to use \*(L"after_render\*(R" in Mojolicious.
.PP
.Vb 2
\& use Mojolicious::Lite;
\& use IO::Compress::Gzip \*(Aqgzip\*(Aq;
\&
\& 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 // \*(Aq\*(Aq) =~ /gzip/i;
\& $c\->res\->headers\->append(Vary => \*(AqAccept\-Encoding\*(Aq);
\&
\& # Compress content with gzip
\& $c\->res\->headers\->content_encoding(\*(Aqgzip\*(Aq);
\& gzip $output, \emy $compressed;
\& $$output = $compressed;
\& };
\&
\& get \*(Aq/\*(Aq => {template => \*(Aqhello\*(Aq, title => \*(AqHello\*(Aq, gzip => 1};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ hello.html.ep
\&
\&
\& <%= title %>
\& Compressed content.
\&
.Ve
.SS "Streaming"
.IX Subsection "Streaming"
You don't have to render all content at once, the method
\&\*(L"write\*(R" in Mojolicious::Controller can also be used to stream a series of
smaller chunks.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\&
\& # Prepare body
\& my $body = \*(AqHello World!\*(Aq;
\& $c\->res\->headers\->content_length(length $body);
\&
\& # Start writing directly with a drain callback
\& my $drain;
\& $drain = sub {
\& my $c = shift;
\& my $chunk = substr $body, 0, 1, \*(Aq\*(Aq;
\& $drain = undef unless length $body;
\& $c\->write($chunk, $drain);
\& };
\& $c\->$drain;
\& };
\&
\& app\->start;
.Ve
.PP
The drain callback will be executed whenever the entire previous chunk of data
has actually been written.
.PP
.Vb 4
\& HTTP/1.1 200 OK
\& Date: Sat, 13 Sep 2014 16:48:29 GMT
\& Content\-Length: 12
\& Server: Mojolicious (Perl)
\&
\& Hello World!
.Ve
.SS "Chunked transfer encoding"
.IX Subsection "Chunked transfer encoding"
For very dynamic content you might not know the response content length in
advance, that's where the chunked transfer encoding and
\&\*(L"write_chunk\*(R" in Mojolicious::Controller come in handy. A common use would be
to send the \f(CW\*(C`head\*(C'\fR section of an \s-1HTML\s0 document to the browser in advance and
speed up preloading of referenced images and stylesheets.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $c = shift;
\& $c\->write_chunk(\*(AqExample\*(Aq => sub {
\& my $c = shift;
\& $c\->finish(\*(AqExample\*(Aq);
\& });
\& };
\&
\& app\->start;
.Ve
.PP
The optional drain callback ensures that all previous chunks have been written
before processing continues. To end the stream you can call
\&\*(L"finish\*(R" in Mojolicious::Controller or write an empty chunk of data.
.PP
.Vb 4
\& HTTP/1.1 200 OK
\& Date: Sat, 13 Sep 2014 16:48:29 GMT
\& Transfer\-Encoding: chunked
\& Server: Mojolicious (Perl)
\&
\& 29
\& Example
\& 1b
\& Example
\& 0
.Ve
.PP
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.
.SS "Encoding"
.IX Subsection "Encoding"
Templates stored in files are expected to be \f(CW\*(C`UTF\-8\*(C'\fR by default, but that can
be easily changed with \*(L"encoding\*(R" in Mojolicious::Renderer.
.PP
.Vb 1
\& $app\->renderer\->encoding(\*(Aqkoi8\-r\*(Aq);
.Ve
.PP
All templates from the \f(CW\*(C`DATA\*(C'\fR section are bound to the encoding of the Perl
script.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/heart\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ heart.html.ep
\& I ♥ Mojolicious!
.Ve
.SS "Base64 encoded \s-1DATA\s0 files"
.IX Subsection "Base64 encoded DATA files"
Base64 encoded static files such as images can be easily stored in the \f(CW\*(C`DATA\*(C'\fR
section of your application, similar to templates.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& get \*(Aq/\*(Aq => {text => \*(AqI ♥ Mojolicious!\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ favicon.ico (base64)
\& ...base64 encoded image...
.Ve
.SS "Inflating \s-1DATA\s0 templates"
.IX Subsection "Inflating DATA templates"
Templates stored in files get preferred over files from the \f(CW\*(C`DATA\*(C'\fR section,
this allows you to include a default set of templates in your application that
the user can later customize. The command Mojolicious::Command::inflate will
write all templates and static files from the \f(CW\*(C`DATA\*(C'\fR section into actual files
in the \f(CW\*(C`templates\*(C'\fR and \f(CW\*(C`public\*(C'\fR directories.
.PP
.Vb 1
\& $ ./myapp.pl inflate
.Ve
.SS "Customizing the template syntax"
.IX Subsection "Customizing the template syntax"
You can easily change the whole template syntax by loading
Mojolicious::Plugin::EPRenderer with a custom configuration.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& plugin EPRenderer => {
\& name => \*(Aqmustache\*(Aq,
\& template => {
\& tag_start => \*(Aq{{\*(Aq,
\& tag_end => \*(Aq}}\*(Aq
\& }
\& };
\&
\& get \*(Aq/:name\*(Aq => {name => \*(AqAnonymous\*(Aq} => \*(Aqindex\*(Aq;
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ index.html.mustache
\& Hello {{= $name }}.
.Ve
.PP
Mojo::Template contains the whole list of available options.
.SS "Adding your favorite template system"
.IX Subsection "Adding your favorite template system"
Maybe you would prefer a different template system than \f(CW\*(C`ep\*(C'\fR, which is provided
by Mojolicious::Plugin::EPRenderer, and there is not already a plugin on \s-1CPAN\s0
for your favorite one. All you have to do, is to add a new \f(CW\*(C`handler\*(C'\fR with
\&\*(L"add_handler\*(R" in Mojolicious::Renderer when \f(CW\*(C`register\*(C'\fR is called.
.PP
.Vb 2
\& package Mojolicious::Plugin::MyRenderer;
\& use Mojo::Base \*(AqMojolicious::Plugin\*(Aq;
\&
\& 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_template = $options\->{inline};
\&
\& # Check for appropriate template in "templates" directories
\& my $template_path = $renderer\->template_path($options);
\&
\& # Check for appropriate template in DATA sections
\& my $data_template = $renderer\->get_data_template($options);
\&
\& # This part is up to you and your template system :)
\& ...
\&
\& # Pass the rendered result back to the renderer
\& $$output = \*(AqHello World!\*(Aq;
\&
\& # Or just die if an error occurs
\& die \*(AqSomething went wrong with the template\*(Aq;
\& });
\& }
\&
\& 1;
.Ve
.PP
An \f(CW\*(C`inline\*(C'\fR template, if provided by the user, will be passed along with the
options. You can use \*(L"template_path\*(R" in Mojolicious::Renderer to search the
\&\f(CW\*(C`templates\*(C'\fR directories of the application, and
\&\*(L"get_data_template\*(R" in Mojolicious::Renderer to search the \f(CW\*(C`DATA\*(C'\fR sections.
.PP
.Vb 1
\& use Mojolicious::Lite;
\&
\& plugin \*(AqMyRenderer\*(Aq;
\&
\& # Render an inline template
\& get \*(Aq/inline\*(Aq => {inline => \*(Aq...\*(Aq, handler => \*(Aqmine\*(Aq};
\&
\& # Render a template from the DATA section
\& get \*(Aq/data\*(Aq => {template => \*(Aqtest\*(Aq};
\&
\& app\->start;
\& _\|_DATA_\|_
\&
\& @@ test.html.mine
\& ...
.Ve
.SS "Adding a handler to generate binary data"
.IX Subsection "Adding a handler to generate binary data"
By default the renderer assumes that every \f(CW\*(C`handler\*(C'\fR generates characters that
need to be automatically encoded, but this can be easily disabled if you're
generating bytes instead.
.PP
.Vb 2
\& use Mojolicious::Lite;
\& use Storable \*(Aqnfreeze\*(Aq;
\&
\& # Add "storable" handler
\& app\->renderer\->add_handler(storable => sub {
\& my ($renderer, $c, $output, $options) = @_;
\&
\& # Disable automatic encoding
\& delete $options\->{encoding};
\&
\& # Encode data from stash value
\& $$output = nfreeze delete $c\->stash\->{storable};
\& });
\&
\& # Set "handler" value automatically if "storable" value is set already
\& app\->hook(before_render => sub {
\& my ($c, $args) = @_;
\& $args\->{handler} = \*(Aqstorable\*(Aq
\& if exists $args\->{storable} || exists $c\->stash\->{storable};
\& });
\&
\& get \*(Aq/\*(Aq => {storable => {i => \*(Aq♥ mojolicious\*(Aq}};
\&
\& app\->start;
.Ve
.PP
The hook \*(L"before_render\*(R" in Mojolicious can be used to make stash values like
\&\f(CW\*(C`storable\*(C'\fR special, so that they no longer require a \f(CW\*(C`handler\*(C'\fR value to be set
explicitly.
.PP
.Vb 2
\& # Explicit "handler" value
\& $c\->render(storable => {i => \*(Aq♥ mojolicious\*(Aq}, handler => \*(Aqstorable\*(Aq);
\&
\& # Implicit "handler" value (with "before_render" hook)
\& $c\->render(storable => {i => \*(Aq♥ mojolicious\*(Aq});
.Ve
.SH "MORE"
.IX Header "MORE"
You can continue with Mojolicious::Guides now or take a look at the
Mojolicious wiki , which contains a lot
more documentation and examples by many different authors.
.SH "SUPPORT"
.IX Header "SUPPORT"
If you have any questions the documentation might not yet answer, don't
hesitate to ask on the
mailing list or the official \s-1IRC\s0
channel \f(CW\*(C`#mojo\*(C'\fR on \f(CW\*(C`irc.perl.org\*(C'\fR
(chat now! ).