/usr/share/perl5/Mojolicious/Guides/Rendering.pod is in libmojolicious-perl 2.23-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | =encoding utf8
=head1 NAME
Mojolicious::Guides::Rendering - Rendering
=head1 OVERVIEW
This document explains content generation with the L<Mojolicious> renderer.
=head1 CONCEPTS
Essentials every L<Mojolicious> developer should know.
=head2 Renderer
The renderer is a tiny black box turning stash data into actual responses
utilizing multiple template systems and data encoding modules.
{text => 'Hello.'} -> 200 OK, text/html, 'Hello.'
{json => {x => 3}} -> 200 OK, application/json, '{"x":3}'
{text => 'Oops.', status => '410'} -> 410 Gone, text/html, 'Oops.'
Templates can be automatically detected if enough information is provided by
the developer or routes.
Template names are expected to follow the C<name.format.handler> scheme, with
C<name> defaulting to C<controller/action> or the route name, C<format>
defaulting to C<html> and C<handler> to C<ep>.
{controller => 'users', action => 'list'} -> 'users/list.html.ep'
{name => 'foo', format => 'txt'} -> 'foo.txt.ep'
{name => 'foo', handler => 'epl'} -> 'foo.html.epl'
All templates should be in the C<templates> directory of the application
or the C<DATA> section of the class C<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.
=head2 Embedded Perl
L<Mojolicious> includes a minimalistic but very powerful template system out
of the box called Embedded Perl or C<ep> for short.
It allows the embedding of Perl code right into actual content using a small
set of special tags and line start characters.
<% Perl code %>
<%= Perl expression, replaced with XML escaped result %>
<%== Perl expression, replaced with result %>
<%# Comment, useful for debugging %>
<%% Replaced with "<%", useful for generating templates %>
% Perl code line, treated as "<% line =%>"
%= Perl expression line, treated as "<%= line %>"
%== Perl expression line, treated as "<%== line %>"
%# Comment line, 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
C<E<lt>>, C<E<gt>>, C<&>, C<'> and C<"> in results from Perl expressions,
which is the default to prevent XSS attacks against your application.
<%= 'lalala' %>
<%== '<p>test</p>' %>
Only L<Mojo::ByteStream> objects are excluded from automatic escaping.
<%= 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 C<$self>.
$self->stash(name => 'tester');
Hello <%= $name %> from <%= $self->tx->remote_address %>.
There are also many helper functions available, but more about that later.
<%= dumper {foo => 'bar'} %>
=head1 BASICS
Most commonly used features every L<Mojolicious> developer should know about.
=head2 Automatic rendering
The renderer can be manually started by calling the C<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 C<render> manually you can
make sure that templates use the current controller instance and not the
default controller specified in the C<controller_class> attribute of the
application class.
=head2 Rendering templates (C<template>)
The renderer will always try to detect the right template but you can also
use the C<template> stash value to render a specific one.
$self->render(template => 'foo/bar');
Choosing a specific C<format> and C<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 C<render> call are only temporarily assigned to the
stash and get reset again once rendering is finished.
=head2 Rendering inline templates (C<inline>)
Some renderers such as C<ep> allow templates to be passed inline.
$self->render(inline => 'The result is <%= 1 + 1%>.');
Since auto detection depends on a path you might have to supply a C<handler>
too.
$self->render(inline => "<%= shift->param('foo') %>", handler => 'epl');
=head2 Rendering text (C<text>)
Perl characters can be rendered with the C<text> stash value, the given
content will be automatically encoded to bytes.
$self->render(text => 'Hello Wörld!');
=head2 Rendering data (C<data>)
Raw bytes can be rendered with the C<data> stash value, no encoding will be
performed.
$self->render(data => $octets);
=head2 Rendering JSON (C<json>)
The C<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]});
=head2 Partial rendering (C<partial>)
Sometimes you might want to access the rendered result, for example to
generate emails, this can be done using the C<partial> stash value.
my $html = $self->render('mail', partial => 1);
=head2 Status code (C<status>)
Response status codes can be changed with the C<status> stash value.
$self->render(text => 'Oops.', status => 500);
=head2 Content type (C<format>)
The C<Content-Type> header of the response is actually based on the MIME type
mapping of the C<format> stash value.
$self->render(text => 'Hello.', format => 'txt');
These mappings can be easily extended or changed with L<Mojolicious/"types">.
# Application
package MyApp;
use Mojo::Base 'Mojolicious';
sub startup {
my $self = shift;
# Add new MIME type
$self->types->type(txt => 'text/plain; charset=utf-8');
}
1;
=head2 Stash data
Data can be passed to templates through the C<stash> in any of the native
Perl data types.
$self->stash(author => 'Sebastian');
$self->stash(frameworks => ['Catalyst', 'Mojolicious']);
$self->stash(examples => {tweetylicious => 'a microblogging app'});
%= $author
%= $frameworks->[1]
%= $examples->{tweetylicious}
Since everything is just Perl normal control structures just work.
% for my $framework (@$frameworks) {
<%= $framework %> was written by <%= $author %>.
% }
% while (my ($app, $description) = each %$examples) {
<%= $app %> is a <%= $description %>.
% }
=head2 Content negotiation
For resources with different representations and that require truly
C<RESTful> content negotiation you can also use C<respond_to> instead of
C<render>.
# /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 => 'world'}},
xml => {text => '<hello>world</hello>'}
);
The best possible representation will be automatically selected from the
C<Accept> request header, C<format> stash value or C<format> GET/POST
parameter.
$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 C<render> call.
# /hello (Accept: application/json) -> "json"
# /hello (Accept: text/html) -> "html"
# /hello (Accept: image/png) -> "any"
# /hello.json -> "json"
# /hello.html -> "html"
# /hello.png -> "any"
# /hello?format=json -> "json"
# /hello?format=html -> "html"
# /hello?format=png -> "any"
$self->respond_to(
json => {json => {hello => 'world'}},
html => {template => 'hello', message => 'world'},
any => {text => '', status => 204}
);
And if no viable representation could be found, the C<any> fallback will be
used or an empty C<204> response rendered automatically.
=head2 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 C<dumper> helper for example will use L<Data::Dumper> to serialize
whatever data structure you pass it, this can be very useful for debugging.
We differentiate between C<default helpers> which are more general purpose
like C<dumper> and C<tag helpers>, which are template specific and mostly
used to generate C<HTML> tags.
%= javascript '/script.js'
%= javascript begin
var a = 'b';
% end
A list of all built-in helpers can be found in
L<Mojolicious::Plugin::DefaultHelpers> and
L<Mojolicious::Plugin::TagHelpers>.
=head2 Layouts
Most of the time when using C<ep> templates you will want to wrap your
generated content in a HTML skeleton, thanks to layouts that's absolutely
trivial.
@@ foo/bar.html.ep
% layout 'mylayout';
Hello World!
@@ layouts/mylayout.html.ep
<!doctype html><html>
<head><title>MyApp</title></head>
<body><%= content %></body>
</html>
You just select the right layout template with the C<layout> helper and place
the result of the current template with the C<content> helper.
You can also pass along normal stash values to the C<layout> helper.
@@ foo/bar.html.ep
% layout 'mylayout', title => 'Hi there';
Hello World!
@@ layouts/mylayout.html.ep
<!doctype html><html>
<head><title><%= $title %></title></head>
<body><%= content %></body>
</html>
Instead of the C<layout> helper you could also just use the C<layout> stash
value, or call C<render> with the C<layout> argument.
$self->render(template => 'mytemplate', layout => 'mylayout');
To set a C<layout> stash value application wide you can use C<defaults>.
# Application
package MyApp;
use Mojo::Base 'Mojolicious';
sub startup {
my $self = shift;
# Default layout
$self->defaults(layout => 'mylayout');
}
1;
=head2 Including partial templates
Like most helpers the C<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 C<include> you could also just call C<render> with the C<partial>
argument.
@@ foo/bar.html.ep
<!doctype html><html>
%= $self->render('header', partial => 1)
<body>Bar</body>
</html>
@@ header.html.ep
<head><title>Howdy</title></head>
But there is one small difference between the two, if you pass stash values
to C<include>, they will get localized automatically and are only available
in the partial template.
@@ foo/bar.html.ep
<!doctype html><html>
%= include 'header', title => 'Hello'
<body>Bar</body>
</html>
@@ header.html.ep
<head><title><%= $title %></title></head>
=head2 Reusable template blocks
It's never fun to repeat yourself, that's why you can build reusable template
blocks in C<ep> that work very similar normal Perl functions.
<% my $block = begin %>
<% my $name = shift; %>
Hello <%= $name %>.
<% end %>
<%= $block->('Sebastian') %>
<%= $block->('Sara') %>
Blocks are always delimited by the C<begin> and C<end> keywords.
% 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;
=head2 Content blocks
Blocks and the C<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
<meta http-equiv="Content-Type" content="text/html">
% end
<div>Hello World!</div>
% content_for header => begin
<meta http-equiv="Pragma" content="no-cache">
% end
@@ layouts/mylayout.html.ep
<!doctype html><html>
<head><%= content_for 'header' %></head>
<body><%= content %></body>
</html>
=head2 Template inheritance
Inheritance takes the layout concept above one step further, it allows you to
build a skeleton template with named C<content> blocks that child templates
can override.
@@ first.html.ep
<!doctype html><html>
<head><title>Hello</title></head>
<body>
%= content header => begin
Default header
% end
<div>Hello World!</div>
%= content footer => begin
Default footer
% end
</body>
</html>
@@ second.html.ep
% extends 'first';
% content header => begin
New header
% end
This chain could go on and on to allow a very high level of template reuse.
=head2 Memorizing template blocks
Compiled templates are always cached in memory, but with the C<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
=head2 Adding helpers
Adding and redefining helpers is very easy, you can use them to do pretty
much everything.
use Mojolicious::Lite;
helper debug => sub {
my ($self, $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 L<Mojo::ByteStream> object can prevent
accidental double escaping.
=head2 Helper plugins
Some helpers might be useful enough for you to share them between multiple
applications, plugins make that very simple.
package Mojolicious::Plugin::DebugHelper;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
$app->helper(debug => sub {
my ($self, $string) = @_;
$self->app->log->debug($string);
});
}
1;
The C<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 C<CPAN> compatible plugin distribution can be
automatically generated.
$ mojo generate plugin DebugHelper
And if you have a C<PAUSE> account (which can be requested at
L<http://pause.perl.org>), you are only a few commands away from relasing it
to C<CPAN>.
$ perl Makefile.PL
$ make test
$ make manifest
$ make dist
$ mojo cpanify -u USER -p PASS Mojolicious-Plugin-DebugHelper-0.01.tar.gz
=head2 Custom C<exception> and C<not_found> templates
While the built-in C<exception> and C<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 L<Mojolicious> will always try to render
C<exception.$mode.$format.*> or C<not_found.$mode.$format.*> before falling
back to the built-in default templates.
@@ not_found.production.html.ep
<!doctype html><html>
<head><title>Page Not Found</title></head>
<body>Page does not seem to exist.</body>
</html>
=head1 ADVANCED
Less commonly used and more powerful features.
=head2 Chunked transfer encoding
For very dynamic content you might not know the response C<Content-Length>
in advance, that's where the C<chunked> C<Transfer-Encoding> comes in handy.
A common use would be to send the C<head> section of an HTML document to the
browser in advance and speed up preloading of referenced images and
stylesheets.
$self->write_chunk('<html><head><title>Example</title></head>', sub {
my $self = shift;
$self->finish('<body>Example</body></html>');
});
The optional drain callback ensures that all previous chunks have been
written before processing continues.
An empty chunk or C<finish> call marks the end of the stream.
29
<html><head><title>Example</title></head>
1b
<body>Example</body></html>
0
Especially in combination with long connection timeouts this can be very
useful for Comet (C<long polling>).
Due to limitations in some web servers this might not work perfectly in all
deployment environments.
=head2 Encoding
Templates stored in files are expected to be C<UTF-8> by default, but that
can be easily changed.
# 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 L<utf8> pragma if necessary.
use Mojolicious::Lite;
use utf8;
get '/heart';
app->start;
__DATA__
@@ heart.html.ep
I ♥ Mojolicious!
=head2 Base64 encoded DATA files
Base64 encoded static files such as images can be easily stored in the
C<DATA> section of your application, similar to templates.
@@ favicon.ico (base64)
...base64 encoded image...
=head2 Inflating DATA templates
Templates stored in files get preferred over files from the C<DATA> section,
this allows you to include a default set of templates in your application
that the user can later customize.
The C<inflate> command will write all templates and static files from the
C<DATA> section into actual files in the C<templates> and C<public>
directories.
$ ./myapp.pl inflate
=head2 Customizing the template syntax
You can easily change the whole template syntax by loading the C<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 }}.
L<Mojo::Template> contains the whole list of available options.
=head2 Adding your favorite template system
Maybe you would prefer a different template system than C<ep>, all you have
to do is add a new C<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 C<DATA> section
the renderer provides methods to help you with that.
=head1 MORE
You can continue with L<Mojolicious::Guides> now or take a look at the
Mojolicious wiki L<http://github.com/kraih/mojo/wiki>, which contains a lot
more documentation and examples by many different authors.
=cut
|