.\" Automatically generated by Pod::Man 2.25 (Pod::Simple 3.16) .\" .\" 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" '' '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 turned on, 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. .ie \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .el \{\ . de IX .. .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Mojolicious::Guides::Rendering 3pm" .TH Mojolicious::Guides::Rendering 3pm "2012-09-05" "perl v5.14.2" "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 .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`name.format.handler\*(C'\fR scheme, with \f(CW\*(C`name\*(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 \& {name => \*(Aqfoo\*(Aq, format => \*(Aqtxt\*(Aq} \-> \*(Aqfoo.txt.ep\*(Aq \& {name => \*(Aqfoo\*(Aq, handler => \*(Aqepl\*(Aq} \-> \*(Aqfoo.html.epl\*(Aq .Ve .PP All templates should be in the \f(CW\*(C`templates\*(C'\fR directories of the application or the \f(CW\*(C`DATA\*(C'\fR section of the class \f(CW\*(C`main\*(C'\fR. .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 allows the embedding of Perl code right into actual content using a small set of special tags and line start characters. .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 =%>" \& %= Perl expression line, treated as "<%= line %>" \& %== Perl expression line, treated as "<%== line %>" \& %# Comment line, treated as "<%# line =%>" \& %% 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; %> \& \& \& % my $i = 10; \& .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; \& 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 \& <%= \*(Aqlalala\*(Aq %> \& <%== \*(Aq

test

\*(Aq %> .Ve .PP Only Mojo::ByteStream objects are excluded from automatic escaping. .PP .Vb 1 \& <%= Mojo::ByteStream\->new(\*(Aq

test

\*(Aq) %> .Ve .PP Newlines 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 can be escaped with another backslash. .PP .Vb 3 \& This will <%= 1 + 1 %> result\e\e \& in multiple\e\e \& lines .Ve .PP 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. .PP .Vb 3 \& <% for (1 .. 3) { %> \& <%= $foo =%> \& <% } %> .Ve .PP 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 \f(CW$self\fR. .PP .Vb 1 \& $self\->stash(name => \*(Aqtester\*(Aq); \& \& Hello <%= $name %> from <%= $self\->tx\->remote_address %>. .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 \& $self\->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. .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. .PP .Vb 1 \& $self\->render(template => \*(Aqfoo/bar\*(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 1 \& $self\->render(template => \*(Aqfoo/bar\*(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 \& $self\->render(\*(Aqfoo/bar\*(Aq); .Ve .SS "Rendering inline templates" .IX Subsection "Rendering inline templates" Some renderers such as \f(CW\*(C`ep\*(C'\fR allow templates to be passed inline. .PP .Vb 1 \& $self\->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 \& $self\->render(inline => "<%= shift\->param(\*(Aqfoo\*(Aq) %>", handler => \*(Aqepl\*(Aq); .Ve .SS "Rendering text" .IX Subsection "Rendering text" Perl characters can be rendered with the \f(CW\*(C`text\*(C'\fR stash value, the given content will be automatically encoded to bytes. .PP .Vb 1 \& $self\->render(text => \*(AqHello Wo\*:rld!\*(Aq); .Ve .SS "Rendering data" .IX Subsection "Rendering data" Raw bytes can be rendered with the \f(CW\*(C`data\*(C'\fR stash value, no encoding will be performed. .PP .Vb 1 \& $self\->render(data => $octets); .Ve .SS "Rendering \s-1JSON\s0" .IX Subsection "Rendering JSON" The \f(CW\*(C`json\*(C'\fR stash value allows you to pass Perl structures to the renderer which get directly encoded to \s-1JSON\s0. .PP .Vb 1 \& $self\->render(json => {foo => [1, \*(Aqtest\*(Aq, 3]}); .Ve .SS "Partial rendering" .IX Subsection "Partial rendering" Sometimes you might want to access the rendered result, for example to generate emails, this can be done using the \f(CW\*(C`partial\*(C'\fR stash value. .PP .Vb 1 \& my $html = $self\->render(\*(Aqmail\*(Aq, partial => 1); .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 \& $self\->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 1 \& $self\->render(text => \*(AqHello.\*(Aq, format => \*(Aqtxt\*(Aq); .Ve .PP These mappings can be easily extended or changed with \*(L"types\*(R" in Mojolicious. .PP .Vb 3 \& # Application \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq; \& \& sub startup { \& my $self = shift; \& \& # Add new MIME type \& $self\->types\->type(txt => \*(Aqtext/plain; charset=utf\-8\*(Aq); \& } \& \& 1; .Ve .SS "Stash data" .IX Subsection "Stash data" Any of the native Perl data types can be passed to templates through the \&\*(L"stash\*(R" in Mojolicious::Controller. .PP .Vb 3 \& $self\->stash(author => \*(AqSebastian\*(Aq); \& $self\->stash(frameworks => [qw(Catalyst Mojolicious)]); \& $self\->stash(examples => {tweetylicious => \*(Aqa microblogging app\*(Aq}); \& \& %= $author \& %= $frameworks\->[1] \& %= $examples\->{tweetylicious} .Ve .PP Since everything is just Perl normal control structures just work. .PP .Vb 3 \& % for my $framework (@$frameworks) { \& <%= $framework %> was written by <%= $author %>. \& % } \& \& % while (my ($app, $description) = each %$examples) { \& <%= $app %> is a <%= $description %>. \& % } .Ve .SS "Content negotiation" .IX Subsection "Content negotiation" For resources with different representations and that require truly \&\f(CW\*(C`RESTful\*(C'\fR 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: text/xml) \-> "xml" \& # /hello.json \-> "json" \& # /hello.xml \-> "xml" \& # /hello?format=json \-> "json" \& # /hello?format=xml \-> "xml" \& $self\->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 \s-1GET/POST\s0 parameter. .PP .Vb 7 \& $self\->respond_to( \& json => {json => {hello => \*(Aqworld\*(Aq}}, \& html => sub { \& $self\->content_for(head => \*(Aq\*(Aq); \& $self\->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" \& $self\->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. .SS "Helpers" .IX Subsection "Helpers" Helpers are little functions you can use in templates and controller code. .PP .Vb 1 \& %= dumper [1, 2, 3] \& \& my $serialized = $self\->dumper([1, 2, 3]); .Ve .PP The helper \*(L"dumper\*(R" in Mojolicious::Plugin::DefaultHelpers for example will use Data::Dumper to serialize whatever data structure you pass it, this can be very useful for debugging. We differentiate between \f(CW\*(C`default helpers\*(C'\fR which are more general purpose like \f(CW\*(C`dumper\*(C'\fR and \f(CW\*(C`tag helpers\*(C'\fR, which are template specific and mostly used to generate \f(CW\*(C`HTML\*(C'\fR tags. .PP .Vb 1 \& %= javascript \*(Aq/script.js\*(Aq \& \& %= javascript begin \& var a = \*(Aqb\*(Aq; \& % end .Ve .PP A list of all built-in helpers can be found in Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers. .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 a \s-1HTML\s0 skeleton, thanks to layouts that's absolutely trivial. .PP .Vb 3 \& @@ 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 3 \& @@ 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 \& $self\->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 3 \& # Application \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq; \& \& sub startup { \& my $self = shift; \& \& # Default layout \& $self\->defaults(layout => \*(Aqmylayout\*(Aq); \& } \& \& 1; .Ve .SS "Including partial templates" .IX Subsection "Including partial templates" Like most helpers \*(L"include\*(R" in Mojolicious::Plugin::DefaultHelpers is just a shortcut to make your life a little easier. .PP .Vb 6 \& @@ foo/bar.html.ep \& \& \& %= include \*(Aqheader\*(Aq \& Bar \& \& \& @@ header.html.ep \& Howdy .Ve .PP Instead of \f(CW\*(C`include\*(C'\fR you could also just call \&\*(L"render\*(R" in Mojolicious::Controller with the \f(CW\*(C`partial\*(C'\fR argument. .PP .Vb 6 \& @@ foo/bar.html.ep \& \& \& %= $self\->render(\*(Aqheader\*(Aq, partial => 1) \& Bar \& \& \& @@ header.html.ep \& Howdy .Ve .PP But there is one small difference between the two, if you pass stash values to \&\f(CW\*(C`include\*(C'\fR, they will get localized automatically and are only available in the partial template. .PP .Vb 6 \& @@ foo/bar.html.ep \& \& \& %= include \*(Aqheader\*(Aq, title => \*(AqHello\*(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 normal Perl functions. .PP .Vb 7 \& @@ welcome.html.ep \& <% my $block = begin %> \& <% my $name = shift; %> \& Hello <%= $name %>. \& <% end %> \& <%= $block\->(\*(AqSebastian\*(Aq) %> \& <%= $block\->(\*(AqSara\*(Aq) %> .Ve .PP Blocks are always delimited by the \f(CW\*(C`begin\*(C'\fR and \f(CW\*(C`end\*(C'\fR keywords. .PP .Vb 8 \& @@ welcome.html.ep \& % my $block = begin \& % my $name = shift; \& Hello <%= $name %>. \& % end \& % for (1 .. 10) { \& %== $block\->(\*(AqSebastian\*(Aq) \& % } .Ve .PP A naive translation to Perl code could look like this. .PP .Vb 10 \& @@ welcome.html.pl \& 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); \& } \& for (1 .. 10) { \& $output .= scalar $block\->(\*(AqSebastian\*(Aq); \& } \& return $output; .Ve .SS "Content blocks" .IX Subsection "Content blocks" Blocks and the helper \*(L"content_for\*(R" in Mojolicious::Plugin::DefaultHelpers can also be used to pass whole sections of the template to the layout. .PP .Vb 9 \& @@ foo/bar.html.ep \& % layout \*(Aqmylayout\*(Aq; \& % content_for header => begin \& \& % end \&
Hello World!
\& % content_for header => begin \& \& % end \& \& @@ layouts/mylayout.html.ep \& \& \& <%= content_for \*(Aqheader\*(Aq %> \& <%= content %> \& .Ve .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 a skeleton template with named blocks that child templates can override. .PP .Vb 10 \& @@ first.html.ep \& \& \& Hello \& \& %= 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 .Ve .PP This chain could go on and on to allow a very high level of template reuse. .SS "Memorizing template blocks" .IX Subsection "Memorizing template blocks" Compiled templates are always cached in memory, but with the helper \&\*(L"memorize\*(R" in Mojolicious::Plugin::DefaultHelpers you can go one step further and prevent template blocks from getting executed more than once. .PP .Vb 5 \& @@ cached.html.ep \& % use Time::Piece; \& %= memorize begin \& This template was compiled at <%= localtime\->hms %>. \& % end .Ve .SS "Adding helpers" .IX Subsection "Adding helpers" Adding and redefining helpers is very easy, you can use them to do pretty much everything. .PP .Vb 1 \& use Mojolicious::Lite; \& \& helper debug => sub { \& my ($self, $string) = @_; \& $self\->app\->log\->debug($string); \& }; \& \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& $self\->debug(\*(Aqaction\*(Aq); \& } => \*(Aqindex\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& % debug \*(Aqtemplate\*(Aq; .Ve .PP Helpers can also accept template blocks as last argument, this for example allows very pleasant to use tag helpers and filters. .PP .Vb 2 \& use Mojolicious::Lite; \& use Mojo::ByteStream; \& \& helper trim_newline => sub { \& my ($self, $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 Wrapping the helper result into a Mojo::ByteStream object can prevent accidental double escaping. .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 ($self, $string) = @_; \& $self\->app\->log\->debug($string); \& }); \& } \& \& 1; .Ve .PP The \f(CW\*(C`register\*(C'\fR method will be called when you load the plugin. .PP .Vb 1 \& use Mojolicious::Lite; \& \& plugin \*(AqDebugHelper\*(Aq; \& \& get \*(Aq/\*(Aq => sub { \& my $self = shift; \& $self\->debug(\*(AqIt works.\*(Aq); \& $self\->render_text(\*(AqHello.\*(Aq); \& }; \& \& app\->start; .Ve .PP A skeleton for a full \f(CW\*(C`CPAN\*(C'\fR 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 relasing it to \f(CW\*(C`CPAN\*(C'\fR. .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 \f(CW\*(C`CPAN\*(C'\fR. .PP .Vb 7 \& $ mojo generate plugin AlertAssets \& $ mkdir AlertAssets/lib/Mojolicious/Plugin/AlertAssets \& $ cd 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 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 File::Basename \*(Aqdirname\*(Aq; \& use File::Spec::Functions \*(Aqcatdir\*(Aq; \& \& sub register { \& my ($self, $app) = @_; \& \& # Append "templates" and "public" directories \& my $base = catdir(dirname(_\|_FILE_\|_), \*(AqAlertAssets\*(Aq); \& push @{$app\->renderer\->paths}, catdir($base, \*(Aqtemplates\*(Aq); \& push @{$app\->static\->paths}, catdir($base, \*(Aqpublic\*(Aq); \& } \& \& 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 .ie n .SS "Custom ""exception"" and ""not_found"" templates" .el .SS "Custom \f(CWexception\fP and \f(CWnot_found\fP templates" .IX Subsection "Custom exception and not_found templates" While the built-in \f(CW\*(C`exception\*(C'\fR and \f(CW\*(C`not_found\*(C'\fR templates are very useful during development, you most likely want to show your users something more related to your application in production. That's why Mojolicious will always try to render \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 6 \& @@ not_found.production.html.ep \& \& \& Page not found \& Page does not seem to exist. \& .Ve .SH "ADVANCED" .IX Header "ADVANCED" Less commonly used and more powerful features. .SS "Internationalization" .IX Subsection "Internationalization" Thanks to Locale::Maketext all you need for basic internationalization support in your application is the plugin Mojolicious::Plugin::I18N and a few lexicon classes. .PP .Vb 3 \& package MyApp::I18N::de; \& use Mojo::Base \-strict; \& use base \*(AqMyApp::I18N\*(Aq; \& \& our %Lexicon = (\*(AqHello World\*(Aq => \*(AqHallo Welt\*(Aq); \& \& package main; \& use Mojolicious::Lite; \& \& plugin I18N => {namespace => \*(AqMyApp::I18N\*(Aq}; \& \& get \*(Aq/\*(Aq => \*(Aqhello\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ hello.html.ep \& <%=l \*(AqHello World\*(Aq %>! .Ve .PP Preferred languages will be automatically detected from the \f(CW\*(C`Accept\-Language\*(C'\fR header or can be manually changed with the helper \&\*(L"languages\*(R" in Mojolicious::Plugin::I18N. .PP .Vb 1 \& $ ./myapp.pl get \-H \*(AqAccept\-Language: de\*(Aq / .Ve .SS "Chunked transfer encoding" .IX Subsection "Chunked transfer encoding" For very dynamic content you might not know the response \f(CW\*(C`Content\-Length\*(C'\fR in advance, that's where the \f(CW\*(C`chunked\*(C'\fR \f(CW\*(C`Transfer\-Encoding\*(C'\fR comes 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 4 \& $self\->write_chunk(\*(AqExample\*(Aq, sub { \& my $self = shift; \& $self\->finish(\*(AqExample\*(Aq); \& }); .Ve .PP The optional drain callback ensures that all previous chunks have been written before processing continues. An empty chunk or call to \&\*(L"finish\*(R" in Mojolicious::Controller marks the end of the stream. .PP .Vb 5 \& 29 \& Example \& 1b \& Example \& 0 .Ve .PP Especially in combination with long inactivity timeouts this can be very useful for Comet (\f(CW\*(C`long polling\*(C'\fR). 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. .PP .Vb 3 \& # Application \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq; \& \& sub startup { \& my $self = shift; \& \& # Different encoding \& $self\->renderer\->encoding(\*(Aqkoi8\-r\*(Aq); \& } \& \& 1; .Ve .PP All templates from the \s-1DATA\s0 section are bound to the encoding of the Perl script, so don't forget to use the utf8 pragma if necessary. .PP .Vb 2 \& use Mojolicious::Lite; \& use utf8; \& \& get \*(Aq/heart\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ heart.html.ep \& I X 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 2 \& @@ 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 \f(CW\*(C`inflate\*(C'\fR command 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 the \f(CW\*(C`ep_renderer\*(C'\fR plugin 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/\*(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, all you have to do is add a new \f(CW\*(C`handler\*(C'\fR. .PP .Vb 1 \& use Mojolicious::Lite; \& \& app\->renderer\->add_handler( \& mine => sub { \& my ($r, $c, $output, $options) = @_; \& \& # One time use inline template \& my $inline = $options\->{inline}; \& \& # Generate relative template path \& my $name = $r\->template_name($options); \& \& # Try to find appropriate template in DATA section \& my $content = $r\->get_data_template($options, $name); \& \& # Generate absolute template path \& my $path = $r\->template_path($options); \& \& # This part is up to you and your template system :) \& ... \& \& # Pass the rendered result back to the renderer \& $$output = \*(AqThe rendered result\*(Aq; \& \& # Return true if rendering succeeded and false if it didn\*(Aqt \& return 1; \& } \& ); \& \& get \*(Aq/\*(Aq => \*(Aqindex\*(Aq; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.mine \& ... .Ve .PP Since most template systems don't support templates in the \f(CW\*(C`DATA\*(C'\fR section the renderer provides methods to help you with that. .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.