Mojolicious::Guides::Rendering man page on Fedora

Man page or keyword search:  
man Server   31170 pages
apropos Keyword Search (all sections)
Output format
Fedora logo
[printable version]

Mojolicious::Guides::RUserrContributed Perl DMojolicious::Guides::Rendering(3)

NAME
       Mojolicious::Guides::Rendering - Rendering

OVERVIEW
       Generating content with the Mojolicious renderer.

CONCEPTS
       Essentials every Mojolicious developer should know.

   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 "name.format.handler" scheme, with "name" defaulting to
       "controller/action" or the route name, "format" defaulting to "html"
       and "handler" to "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 "templates" directory of the application
       or the "DATA" section of the class "main".

	 __DATA__
	 @@ time.html.ep
	 <!doctype html><html>
	   <head><title>Time</title></head>
	   <body><%= localtime time %></body>
	 </html>

	 @@ hello.txt.ep
	 ...

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

   Embedded Perl
       Mojolicious includes a minimalistic but very powerful template system
       out of the box called Embedded Perl or "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, treated as "<%# line =%>"
	 %% 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>

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

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

       Only Mojo::ByteStream objects are excluded from automatic escaping.

	 <%= b('<p>test</p>') %>

       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 instance as $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'} %>

BASICS
       Most commonly used features every Mojolicious developer should know
       about.

   Automatic Rendering
       The renderer can be manually started by calling the "render" controller
       method, but that's usually not necessary, because it will get
       automatically called if nothing has been rendered after the routes
       dispatcher 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 "render" manually you
       can make sure that templates use the current controller instance and
       not the default controller specified in the "controller_class"
       attribute of the application class.

   Rendering Templates ("template")
       The renderer will always try to detect the right template but you can
       also use the "template" stash value to render a specific one.

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

       Choosing a specific "format" and "handler" is just as easy.

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

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

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

       All values passed to the "render" call are only temporarily assigned to
       the stash and get reset again once rendering is finished.

   Rendering Inline Templates ("inline")
       Some renderers such as "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
       "handler" too.

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

   Rendering Text ("text")
       Perl characters can be rendered with the "text" stash value, the given
       content will be automatically encoded to bytes.

	 $self->render(text => 'Hello Woerld!');

   Rendering Data ("data")
       Raw bytes can be rendered with the "data" stash value, no encoding will
       be performed.

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

   Rendering JSON ("json")
       The "json" stash value allows you to pass Perl structures to the
       renderer which get directly encoded to JSON.

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

   Partial Rendering ("partial")
       Sometimes you might want to access the rendered result, for example to
       generate emails, this can be done using the "partial" stash value.

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

   Status Code ("status")
       Response status codes can be changed with the "status" stash value.

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

   Content Type ("format")
       The "Content-Type" header of the response is actually based on the MIME
       type mapping of the "format" stash value.

	 $self->render(text => 'Hello!', format => 'txt');

       These mappings can be easily extended or changed with "types" in
       Mojolicious.

	 # 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;

   Stash Data
       Data can be passed to templates through the "stash" in any of the
       native Perl data types.

	 $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 %>.
	 <% } %>

   Content Negotiation
       For resources with different representations and that require truly
       "RESTful" content negotiation you can also use "respond_to" instead of
       "render".

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

       The best possible representation will be automatically selected from
       the "Accept" request header, "format" stash value or "format" GET/POST
       parameter.

	 $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.

	 # "Accept: application/json" -> "json"
	 # "Accept: text/html"	      -> "html"
	 # "Accept: image/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 "any" fallback will
       be used or an empty 204 response rendered automatically.

   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 "dumper" helper for example will use Data::Dumper to serialize
       whatever data structure you pass it, this can be very useful for
       debugging.  We differentiate between "default helpers" which are more
       general purpose like "dumper" and "tag helpers", which are template
       specific and mostly used to generate "HTML" tags.

	 <%= javascript '/script.js' %>

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

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

   Layouts
       Most of the time when using "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 "layout" helper and
       place the result of the current template with the "content" helper.
       You can also pass along normal stash values to the "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 "layout" helper you could also just use the "layout"
       stash value, or call "render" with the "layout" argument.

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

       To set a "layout" stash value application wide you can use "defaults".

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

	 sub startup {
	   my $self = shift;

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

	 1;

   Including Partial Templates
       Like most helpers the "include" helper 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 "include" you could also just call "render" with the
       "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 "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>

   Reusable Template Blocks
       It's never fun to repeat yourself, that's why you can build reusable
       template blocks in "ep" that work very similar normal Perl functions.

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

       Blocks are always delimited by the "begin" and "end" keywords.

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

       A naive translation to equivalent Perl code could look like this.

	 my $output = '';
	 my $block  = sub {
	   my $name   = shift;
	   my $output = '';
	   $output .= "Hello $name.";
	   return $output;
	 }
	 for (1 .. 10) {
	   $output .= $block->('Sebastian');
	 }
	 print $output;

   Content Blocks
       Blocks and the "content_for" helper can also be used to pass whole
       sections of the template to the layout.

	 @@ foo/bar.html.ep
	 % layout 'mylayout';
	 <% content_for header => begin %>
	   <title>MyApp!</title>
	 <% end %>
	 Hello World!
	 <% 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>

   Template Inheritance
       Inheritance takes the layout concept above one step further.  Unlike
       "content_for" the "content" helper does not allow appending to existing
       values, this makes it possible to overload whole template sections.
       The only difference between "layout" and "extends" is that extended
       templates don't get prefixed with "layouts/".

	 @@ first.html.ep
	 %# "<div>First header!First footer!</div>"
	 <div>
	 <%= content header => begin %>
	   First header!
	 <% end %>
	 <%= content footer => begin %>
	   First footer!
	 <% end %>
	 </div>

	 @@ second.html.ep
	 %# "<div>Second header!First footer!</div>"
	 % extends 'first';
	 <% content header => begin %>
	   Second header!
	 <% end %>

	 @@ third.html.ep
	 %# "<div>Second header!Third footer!</div>"
	 % extends 'second';
	 <% content footer => begin %>
	   Third footer!
	 <% end %>

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

   Memorizing Template Blocks
       Compiled templates are always cached in memory, but with the "memorize"
       helper you can go one step further and prevent template blocks from
       being executed more than once.

	 <%= memorize begin %>
	   This template was compiled at <%= localtime time %>.
	 <% end %>

   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, $string) = @_;
	   $self->app->log->debug($string);
	 };

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

	 app->start;
	 __DATA__

	 @@ index.html.ep
	 % debug '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 Mojo::ByteStream object can prevent
       accidental double escaping.

   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, $string) = @_;
	     $self->app->log->debug($string);
	   });
	 }

	 1;

       The "register" method will be called when you load the plugin.

	 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 "PAUSE" account (which can be requested at
       <http://pause.perl.org>), you are only a few commands away from
       relasing 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

   Mode Specific "exception" And "not_found" Templates
       While the built-in "exception" and "not_found" 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 "exception.$mode.$format.*" or
       "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>Something bad happened!</body>
	 </html>

	 @@ not_found.production.html.ep
	 <!doctype html><html>
	   <head><title>Page Not Found</title></head>
	   <body>Page does not seem to exist.</body>
	 </html>

ADVANCED
       Less commonly used and more powerful features.

   Chunked Transfer Encoding
       For very dynamic content you might not know the response
       "Content-Length" in advance, that's where the "chunked"
       "Transfer-Encoding" comes in handy.  A common use would be to send the
       "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>');
	 $self->write_chunk('<link href="example.css" rel="stylesheet"');
	 $self->write_chunk(' type="text/css"></head>', sub {
	   my $self = shift;
	   $self->write_chunk('<body>Example</body></html>');
	   $self->write_chunk('');
	 });

       The optional drain callback ensures that all previous chunks have been
       written before processing continues.  An empty chunk marks the end of
       the stream.

	 22
	 <html><head><title>Example</title>
	 29
	 <link href="example.css" rel="stylesheet"
	 17
	  type="text/css"></head>
	 1C
	 <body>Example</body></html>
	 0

       Especially in combination with long connection 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.

   Encoding
       Templates stored in files are expected to be "UTF-8" by default, but
       that can be easily changed.

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

	 sub startup {
	   my $self = shift;

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

	 1;

       All templates from the DATA section are bound to the encoding of the
       Perl script, so don't forget to use the utf8 pragma if necessary.

	 use Mojolicious::Lite;
	 use utf8;

	 get '/heart';

	 app->start;
	 __DATA__

	 @@ heart.html.ep
	 I X Mojolicious!

   Base64 Encoded DATA Files
       Base64 encoded static files such as images can be easily stored in the
       "DATA" section of your application, similar to templates.

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

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

	 $ ./myapp.pl inflate

   Customizing The Template Syntax
       You can easily change the whole template syntax by loading the
       "ep_renderer" plugin with a custom configuration.

	 use Mojolicious::Lite;

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

	 get '/' => 'index';

	 app->start;
	 __DATA__

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

       Mojo::Template contains the whole list of available options.

   Adding Your Favorite Template System
       Maybe you would prefer a different template system than "ep", all you
       have to do is add a new "handler".

	 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 = 'The rendered result!';
	   }
	 );

	 get '/' => 'index';

	 app->start;
	 __DATA__

	 @@ index.html.mine
	 ...

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

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

perl v5.14.1			  2011-09-10 Mojolicious::Guides::Rendering(3)
[top]

List of man pages available for Fedora

Copyright (c) for man pages and the logo by the respective OS vendor.

For those who want to learn more, the polarhome community provides shell access and support.

[legal] [privacy] [GNU] [policy] [cookies] [netiquette] [sponsors] [FAQ]
Tweet
Polarhome, production since 1999.
Member of Polarhome portal.
Based on Fawad Halim's script.
....................................................................
Vote for polarhome
Free Shell Accounts :: the biggest list on the net