/usr/share/perl5/Mojolicious/Guides/Rendering.pod is in libmojolicious-perl 7.59+dfsg-1ubuntu1.
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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 | =encoding utf8
=head1 NAME
Mojolicious::Guides::Rendering - Rendering content
=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<template.format.handler> scheme, with C<template> 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'
{template => 'foo', format => 'txt'} -> 'foo.txt.ep'
{template => 'foo', handler => 'epl'} -> 'foo.html.epl'
The C<controller> value gets converted from C<CamelCase> to C<snake_case> using
L<Mojo::Util/"decamelize"> and C<-> characters replaced with C</>.
{controller => 'My::Users', action => 'add'} -> 'my/users/add.html.ep'
{controller => 'my-users', action => 'show'} -> 'my/users/show.html.ep'
All templates should be in the C<templates> directories of the application,
which can be customized with L<Mojolicious::Renderer/"paths">, or one of the
the C<DATA> sections from L<Mojolicious::Renderer/"classes">.
__DATA__
@@ time.html.ep
% use Time::Piece;
% my $now = localtime;
<!DOCTYPE html>
<html>
<head><title>Time</title></head>
<body>The time is <%= $now->hms %>.</body>
</html>
@@ hello.txt.ep
...
The renderer can be easily extended to support additional template systems with
plugins, but more about that later.
=head2 Embedded Perl
L<Mojolicious> includes a minimalistic but very powerful template system out of
the box called Embedded Perl or C<ep> for short. It is based on
L<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 L<strict>, L<warnings>, L<utf8> and Perl 5.10 L<features|feature> are
automatically enabled.
<% 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
Tags and lines work pretty much the same, but depending on context one will
usually look a bit better. Semicolons get automatically appended to all
expressions.
<% my $i = 10; %>
<ul>
<% for my $j (1 .. $i) { %>
<li>
<%= $j %>
</li>
<% } %>
</ul>
% my $i = 10;
<ul>
% for my $j (1 .. $i) {
<li>
%= $j
</li>
% }
</ul>
Aside from differences in whitespace handling, both examples generate similar
Perl code, a naive translation could look like this.
my $output = '';
my $i = 10;
$output .= '<ul>';
for my $j (1 .. $i) {
$output .= '<li>';
$output .= xml_escape scalar + $j;
$output .= '</li>';
}
$output .= '</ul>';
return $output;
An additional equal sign can be used to disable escaping of the characters
C<E<lt>>, C<E<gt>>, C<&>, C<'> and C<"> in results from Perl expressions, which
is the default to prevent XSS attacks against your application.
<%= 'I ♥ Mojolicious!' %>
<%== '<p>I ♥ Mojolicious!</p>' %>
Only L<Mojo::ByteStream> objects are excluded from automatic escaping.
<%= b('<p>I ♥ Mojolicious!</p>') %>
Whitespace characters around tags can be trimmed by adding an additional equal
sign to the end of a tag.
<% for (1 .. 3) { %>
<%= 'Trim all whitespace characters around this expression' =%>
<% } %>
Newline characters can be escaped with a backslash.
This is <%= 1 + 1 %> a\
single line
And a backslash in front of a newline character can be escaped with another
backslash.
This will <%= 1 + 1 %> result\\
in multiple\\
lines
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.
There is <%= 1 + 1 %> no newline at the end here\
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 C<$self> and C<$c>.
$c->stash(name => 'tester');
Hello <%= $name %> from <%= $c->tx->remote_address %>.
A prefix like C<myapp.*> is commonly used for stash values that you don't want
to expose in templates.
$c->stash('myapp.name' => 'tester');
There are also many helper functions available, but more about that later.
<%= dumper {foo => 'bar'} %>
=head1 BASICS
Most commonly used features every L<Mojolicious> developer should know about.
=head2 Automatic rendering
The renderer can be manually started by calling the method
L<Mojolicious::Controller/"render">, but that's usually not necessary, because
it will get automatically called if nothing has been rendered after the router
finished its work. This also means you can have routes pointing only to
templates without actual actions.
$c->render;
There is one big difference though, by calling it manually you can make sure
that templates use the current controller object, and not the default
controller specified with the attribute L<Mojolicious/"controller_class">.
$c->render_later;
You can also disable automatic rendering with the method
L<Mojolicious::Controller/"render_later">, which can be very useful to delay
rendering when a non-blocking operation has to be performed first.
=head2 Rendering templates
The renderer will always try to detect the right template, but you can also use
the C<template> stash value to render a specific one. Everything before the
last slash will be interpreted as the subdirectory path in which to find the
template.
# foo/bar/baz.*.*
$c->render(template => 'foo/bar/baz');
Choosing a specific C<format> and C<handler> is just as easy.
# foo/bar/baz.txt.epl
$c->render(template => 'foo/bar/baz', format => 'txt', handler => 'epl');
Because rendering a specific template is the most common task it also has a
shortcut.
$c->render('foo/bar/baz');
If you're not sure in advance if a template actually exists, you can also use
the method L<Mojolicious::Controller/"render_maybe"> to try multiple
alternatives.
$c->render_maybe('localized/baz') or $c->render('foo/bar/baz');
=head2 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<Mojolicious::Controller/"render_to_string">.
my $html = $c->render_to_string('mail');
No encoding will be performed, making it easy to reuse the result in other
templates or to generate binary data.
my $pdf = $c->render_to_string('invoice', format => 'pdf');
$c->render(data => $pdf, format => 'pdf');
All arguments passed will get localized automatically and are only available
during this render operation.
=head2 Template variants
To make your application look great on many different devices you can also use
the C<variant> stash value to choose between different variants of your
templates.
# foo/bar/baz.html+phone.ep
# foo/bar/baz.html.ep
$c->render('foo/bar/baz', variant => 'phone');
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.
=head2 Rendering inline templates
Some renderers such as C<ep> allow templates to be passed C<inline>.
$c->render(inline => 'The result is <%= 1 + 1 %>.');
Since auto-detection depends on a path you might have to supply a C<handler>
too.
$c->render(inline => "<%= shift->param('foo') %>", handler => 'epl');
=head2 Rendering text
Characters can be rendered to bytes with the C<text> stash value, the given
content will be automatically encoded with L<Mojolicious::Renderer/"encoding">.
$c->render(text => 'I ♥ Mojolicious!');
=head2 Rendering data
Bytes can be rendered with the C<data> stash value, no encoding will be
performed.
$c->render(data => $bytes);
=head2 Rendering JSON
The C<json> stash value allows you to pass Perl data structures to the renderer
which get directly encoded to JSON with L<Mojo::JSON>.
$c->render(json => {foo => [1, 'test', 3]});
=head2 Status code
Response status codes can be changed with the C<status> stash value.
$c->render(text => 'Oops.', status => 500);
=head2 Content type
The C<Content-Type> header of the response is actually based on the MIME type
mapping of the C<format> stash value.
# Content-Type: text/plain
$c->render(text => 'Hello.', format => 'txt');
# Content-Type: image/png
$c->render(data => $bytes, format => 'png');
These mappings can be easily extended or changed with L<Mojolicious/"types">.
# Add new MIME type
$app->types->type(md => 'text/markdown');
=head2 Stash data
Any of the native Perl data types can be passed to templates as references
through the L<Mojolicious::Controller/"stash">.
$c->stash(description => 'web framework');
$c->stash(frameworks => ['Catalyst', 'Mojolicious']);
$c->stash(spinoffs => {minion => 'job queue'});
%= $description
%= $frameworks->[1]
%= $spinoffs->{minion}
Since everything is just Perl normal control structures just work.
% for my $framework (@$frameworks) {
<%= $framework %> is a <%= $description %>.
% }
% if (my $description = $spinoffs->{minion}) {
Minion is a <%= $description %>.
% }
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<Mojolicious::Plugin::DefaultHelpers/"stash">.
% if (my $spinoffs = stash 'spinoffs') {
Minion is a <%= $spinoffs->{minion} %>.
% }
=head2 Helpers
Helpers are little functions you can use in templates as well as application
and controller code.
# Template
%= dumper [1, 2, 3]
# Application
my $serialized = $app->dumper([1, 2, 3]);
# Controller
my $serialized = $c->dumper([1, 2, 3]);
We differentiate between default helpers, which are more general purpose like
L<Mojolicious::Plugin::DefaultHelpers/"dumper">, and tag helpers like
L<Mojolicious::Plugin::TagHelpers/"link_to">, which are template specific and
mostly used to generate HTML tags.
%= link_to Mojolicious => 'http://mojolicious.org'
In controllers you can also use the method L<Mojolicious::Controller/"helpers">
to fully qualify helper calls and ensure that they don't conflict with existing
methods you may already have.
my $serialized = $c->helpers->dumper([1, 2, 3]);
A list of all built-in helpers can be found in
L<Mojolicious::Plugin::DefaultHelpers> and L<Mojolicious::Plugin::TagHelpers>.
=head2 Content negotiation
For resources with different representations and that require truly RESTful
content negotiation you can also use L<Mojolicious::Controller/"respond_to">
instead of L<Mojolicious::Controller/"render">.
# /hello (Accept: application/json) -> "json"
# /hello (Accept: application/xml) -> "xml"
# /hello.json -> "json"
# /hello.xml -> "xml"
# /hello?format=json -> "json"
# /hello?format=xml -> "xml"
$c->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> C<GET>/C<POST>
parameter and stored in the C<format> stash value. To change MIME type mappings
for the C<Accept> request header or the C<Content-Type> response header you can
use L<Mojolicious/"types">.
$c->respond_to(
json => {json => {hello => 'world'}},
html => sub {
$c->content_for(head => '<meta name="author" content="sri">');
$c->render(template => 'hello', message => 'world')
}
);
Callbacks can be used for representations that are too complex to fit into a
single render call.
# /hello (Accept: application/json) -> "json"
# /hello (Accept: text/html) -> "html"
# /hello (Accept: image/png) -> "any"
# /hello.json -> "json"
# /hello.html -> "html"
# /hello.png -> "any"
# /hello?format=json -> "json"
# /hello?format=html -> "html"
# /hello?format=png -> "any"
$c->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.
# /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('html', 'xml')) {
...
}
For even more advanced negotiation logic you can also use the helper
L<Mojolicious::Plugin::DefaultHelpers/"accepts">.
=head2 Rendering C<exception> and C<not_found> pages
By now you've probably already encountered the built-in C<404> (Not Found) and
C<500> (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<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>exception">
and L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>not_found">.
use Mojolicious::Lite;
use Scalar::Util 'looks_like_number';
get '/divide/:dividend/by/:divisor' => sub {
my $c = shift;
my $dividend = $c->param('dividend');
my $divisor = $c->param('divisor');
# 404
return $c->reply->not_found
unless looks_like_number $dividend && looks_like_number $divisor;
# 500
return $c->reply->exception('Division by zero!') if $divisor == 0;
# 200
$c->render(text => $dividend / $divisor);
};
app->start;
You can also change the templates of those pages, since you most likely want to
show your users something more closely related to your application in
production. The renderer will always try to find C<exception.$mode.$format.*>
or C<not_found.$mode.$format.*> before falling back to the built-in default
templates.
use Mojolicious::Lite;
get '/dies' => sub { die 'Intentional error' };
app->start;
__DATA__
@@ exception.production.html.ep
<!DOCTYPE html>
<html>
<head><title>Server error</title></head>
<body>
<h1>Exception</h1>
<p><%= $exception->message %></p>
<h1>Stash</h1>
<pre><%= dumper $snapshot %></pre>
</body>
</html>
The hook L<Mojolicious/"before_render"> makes even more advanced customizations
possible by allowing you to intercept and modify the arguments passed to the
renderer.
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 'exception';
# Switch to JSON rendering if content negotiation allows it
$args->{json} = {exception => $args->{exception}} if $c->accepts('json');
};
get '/' => sub { die "This sho...ALL GLORY TO THE HYPNOTOAD!\n" };
app->start;
=head2 Layouts
Most of the time when using C<ep> templates you will want to wrap your
generated content in an HTML skeleton, thanks to layouts that's absolutely
trivial.
use Mojolicious::Lite;
get '/' => {template => 'foo/bar'};
app->start;
__DATA__
@@ foo/bar.html.ep
% layout 'mylayout';
Hello World!
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
<head><title>MyApp</title></head>
<body><%= content %></body>
</html>
You just select the right layout template with the helper
L<Mojolicious::Plugin::DefaultHelpers/"layout"> and place the result of the
current template with the helper
L<Mojolicious::Plugin::DefaultHelpers/"content">. You can also pass along
normal stash values to the C<layout> helper.
use Mojolicious::Lite;
get '/' => {template => 'foo/bar'};
app->start;
__DATA__
@@ foo/bar.html.ep
% layout 'mylayout', title => 'Hi there';
Hello World!
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
<head><title><%= $title %></title></head>
<body><%= content %></body>
</html>
Instead of the C<layout> helper you could also just use the C<layout> stash
value, or call L<Mojolicious::Controller/"render"> with the C<layout> argument.
$c->render(template => 'mytemplate', layout => 'mylayout');
To set a C<layout> stash value application-wide you can use
L<Mojolicious/"defaults">.
$app->defaults(layout => 'mylayout');
Layouts can also be used with L<Mojolicious::Controller/"render_to_string">,
but the C<layout> value needs to be passed as a render argument (not a stash
value).
my $html = $c->render_to_string('reminder', layout => 'mail');
=head2 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<Mojolicious::Plugin::DefaultHelpers/"include"> to include one template into
another.
use Mojolicious::Lite;
get '/' => {template => 'foo/bar'};
app->start;
__DATA__
@@ foo/bar.html.ep
<!DOCTYPE html>
<html>
%= include '_header', title => 'Howdy'
<body>Bar</body>
</html>
@@ _header.html.ep
<head><title><%= $title %></title></head>
You can name partial templates however you like, but a leading underscore is a
commonly used naming convention.
=head2 Reusable template blocks
It's never fun to repeat yourself, that's why you can build reusable template
blocks in C<ep> that work very similar to normal Perl functions, with the
C<begin> and C<end> 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
C<begin> and before C<end>.
use Mojolicious::Lite;
get '/' => 'welcome';
app->start;
__DATA__
@@ welcome.html.ep
<% my $block = begin %>
% my $name = shift;
Hello <%= $name %>.
<% end %>
<%= $block->('Wolfgang') %>
<%= $block->('Baerbel') %>
A naive translation of the template to Perl code could look like this.
my $output = '';
my $block = sub {
my $name = shift;
my $output = '';
$output .= 'Hello ';
$output .= xml_escape scalar + $name;
$output .= '.';
return Mojo::ByteStream->new($output);
};
$output .= xml_escape scalar + $block->('Wolfgang');
$output .= xml_escape scalar + $block->('Baerbel');
return $output;
While template blocks cannot be shared between templates, they are most
commonly used to pass parts of a template to helpers.
=head2 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.
use Mojolicious::Lite;
helper debug => sub {
my ($c, $str) = @_;
$c->app->log->debug($str);
};
get '/' => sub {
my $c = shift;
$c->debug('Hello from an action!');
} => 'index';
app->start;
__DATA__
@@ index.html.ep
% debug 'Hello from a template!';
Helpers can also accept template blocks as last argument, this for example,
allows very pleasant to use tag helpers and filters. Wrapping the helper result
into a L<Mojo::ByteStream> object can prevent accidental double escaping.
use Mojolicious::Lite;
use Mojo::ByteStream;
helper trim_newline => sub {
my ($c, $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
Similar to stash values, you can use a prefix like C<myapp.*> 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.
use Mojolicious::Lite;
helper 'cache_control.no_caching' => sub {
my $c = shift;
$c->res->headers->cache_control('private, max-age=0, no-cache');
};
helper 'cache_control.five_minutes' => sub {
my $c = shift;
$c->res->headers->cache_control('public, max-age=300');
};
get '/news' => sub {
my $c = shift;
$c->cache_control->no_caching;
$c->render(text => 'Always up to date.');
};
get '/some_older_story' => sub {
my $c = shift;
$c->cache_control->five_minutes;
$c->render(text => 'This one can be cached for a bit.');
};
app->start;
While helpers can also be redefined, this should only be done very carefully to
avoid conflicts.
=head2 Content blocks
The helper L<Mojolicious::Plugin::DefaultHelpers/"content_for"> 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.
use Mojolicious::Lite;
get '/' => 'foo';
app->start;
__DATA__
@@ foo.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 'header' %></head>
<body><%= content %></body>
</html>
=head2 Forms
To build HTML forms more efficiently you can use tag helpers like
L<Mojolicious::Plugin::TagHelpers/"form_for">, 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 C<GET> and C<POST>, but not request
methods like C<PUT> or C<DELETE>, they are spoofed with an C<_method> query
parameter.
use Mojolicious::Lite;
get '/' => 'form';
# PUT /nothing
# POST /nothing?_method=PUT
put '/nothing' => sub {
my $c = shift;
# Prevent double form submission with redirect
my $value = $c->param('whatever');
$c->flash(confirmation => "We did nothing with your value ($value).");
$c->redirect_to('form');
};
app->start;
__DATA__
@@ form.html.ep
<!DOCTYPE html>
<html>
<body>
% if (my $confirmation = flash 'confirmation') {
<p><%= $confirmation %></p>
% }
%= form_for nothing => begin
%= text_field whatever => 'I ♥ Mojolicious!'
%= submit_button
% end
</body>
</html>
The methods L<Mojolicious::Controller/"flash"> and
L<Mojolicious::Controller/"redirect_to"> 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.
=head2 Form validation
You can use L<Mojolicious::Controller/"validation"> to validate C<GET> and
C<POST> parameters submitted to your application. All unknown fields will be
ignored by default, so you have to decide which should be required or optional
before you can perform checks on their values. Every check is performed right
away, so you can use the results immediately to build more advanced validation
logic with methods like L<Mojolicious::Validator::Validation/"is_valid">.
use Mojolicious::Lite;
get '/' => sub {
my $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('user')->size(1, 20)->like(qr/^[a-z0-9]+$/);
$validation->required('pass_again')->equal_to('pass')
if $validation->optional('pass')->size(7, 500)->is_valid;
# Render confirmation if validation was successful
$c->render('thanks') unless $validation->has_error;
} => 'index';
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head>
<style>
label.field-with-error { color: #dd7e5e }
input.field-with-error { background-color: #fd9e7e }
</style>
</head>
<body>
%= form_for index => begin
%= label_for user => 'Username (required, 1-20 characters, a-z/0-9)'
<br>
%= text_field 'user', id => 'user'
%= submit_button
<br>
%= label_for pass => 'Password (optional, 7-500 characters)'
<br>
%= password_field 'pass', id => 'pass'
<br>
%= label_for pass_again => 'Password again (equal to the value above)'
<br>
%= password_field 'pass_again', id => 'pass_again'
% end
</body>
</html>
@@ thanks.html.ep
<!DOCTYPE html>
<html><body>Thank you <%= validation->param('user') %>.</body></html>
Form elements generated with tag helpers from
L<Mojolicious::Plugin::TagHelpers> will automatically remember their previous
values and add the class C<field-with-error> for fields that failed validation
to make styling with CSS easier.
<label class="field-with-error" for="user">
Username (required, only characters e-t)
</label>
<input class="field-with-error" type="text" name="user" value="sri">
For a full list of available checks see also
L<Mojolicious::Validator/"CHECKS">.
=head2 Adding form validation checks
Validation checks can be registered with L<Mojolicious::Validator/"add_check">
and return a false value if they were successful. A true value may be used to
pass along additional information which can then be retrieved with
L<Mojolicious::Validator::Validation/"error">.
use Mojolicious::Lite;
# Add "range" check
app->validator->add_check(range => sub {
my ($validation, $name, $value, $min, $max) = @_;
return $value < $min || $value > $max;
});
get '/' => 'form';
post '/test' => sub {
my $c = shift;
# Validate parameters with custom check
my $validation = $c->validation;
$validation->required('number')->range(3, 23);
# Render form again if validation failed
return $c->render('form') if $validation->has_error;
# Prevent double form submission with redirect
$c->flash(number => $validation->param('number'));
$c->redirect_to('form');
};
app->start;
__DATA__
@@ form.html.ep
<!DOCTYPE html>
<html>
<body>
% if (my $number = flash 'number') {
<p>Thanks, the number <%= $number %> was valid.</p>
% }
%= form_for test => begin
% if (my $err = validation->error('number')) {
<p>
%= 'Value is required.' if $err->[0] eq 'required'
%= 'Value needs to be between 3 and 23.' if $err->[0] eq 'range'
</p>
% }
%= text_field 'number'
%= submit_button
% end
</body>
</html>
=head2 Cross-site request forgery
CSRF 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<Mojolicious::Plugin::TagHelpers/"csrf_field">, and validate it with
L<Mojolicious::Validator::Validation/"csrf_protect">.
use Mojolicious::Lite;
get '/' => {template => 'target'};
post '/' => sub {
my $c = shift;
# Check CSRF token
my $validation = $c->validation;
return $c->render(text => 'Bad CSRF token!', status => 403)
if $validation->csrf_protect->has_error('csrf_token');
my $city = $validation->required('city')->param('city');
$c->render(text => "Low orbit ion cannon pointed at $city!")
unless $validation->has_error;
} => 'target';
app->start;
__DATA__
@@ target.html.ep
<!DOCTYPE html>
<html>
<body>
%= form_for target => begin
%= csrf_field
%= label_for city => 'Which city to point low orbit ion cannon at?'
%= text_field 'city', id => 'city'
%= submit_button
%= end
</body>
</html>
For Ajax requests and the like, you can also generate a token directly with the
helper L<Mojolicious::Plugin::DefaultHelpers/"csrf_token">, and then pass it
along with the C<X-CSRF-Token> request header.
=head1 ADVANCED
Less commonly used and more powerful features.
=head2 Template inheritance
Inheritance takes the layout concept above one step further, the helpers
L<Mojolicious::Plugin::DefaultHelpers/"content"> and
L<Mojolicious::Plugin::DefaultHelpers/"extends"> allow you to build skeleton
templates with named blocks that child templates can override.
use Mojolicious::Lite;
# first > mylayout
get '/first' => {template => 'first', layout => 'mylayout'};
# third > second > first > mylayout
get '/third' => {template => 'third', layout => 'mylayout'};
app->start;
__DATA__
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body><%= content %></body>
</html>
@@ first.html.ep
%= content header => begin
Default header
% end
<div>Hello World!</div>
%= content footer => begin
Default footer
% end
@@ second.html.ep
% extends 'first';
% content header => begin
New header
% end
@@ third.html.ep
% extends 'second';
% content footer => begin
New footer
% end
This chain could go on and on to allow a very high level of template reuse.
=head2 Serving static files
Static files are automatically served from the C<public> directories of the
application, which can be customized with L<Mojolicious::Static/"paths">, or one
of the C<DATA> sections from L<Mojolicious::Static/"classes">. And if that's not
enough you can also serve them manually with
L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>static">.
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
$c->reply->static('index.html');
};
get '/some_download' => sub {
my $c = shift;
$c->res->headers->content_disposition('attachment; filename=bar.png;');
$c->reply->static('foo/bar.png');
};
app->start;
=head2 Custom responses
Most response content, static as well as dynamic, gets served through
L<Mojo::Asset::File> and L<Mojo::Asset::Memory> objects. For somewhat static
content, like cached JSON data or temporary files, you can create your own and
use the helper L<Mojolicious::Plugin::DefaultHelpers/"reply-E<gt>asset"> to
serve them while allowing content negotiation to be performed with C<Range>,
C<If-Modified-Since> and C<If-None-Match> headers.
use Mojolicious::Lite;
use Mojo::Asset::File;
get '/leak' => sub {
my $c = shift;
$c->res->headers->content_type('text/plain');
$c->reply->asset(Mojo::Asset::File->new(path => '/etc/passwd'));
};
app->start;
For even more control you can also just skip the helper and use
L<Mojolicious::Controller/"rendered"> to tell the renderer when you're done
generating a response.
use Mojolicious::Lite;
use Mojo::Asset::File;
get '/leak' => sub {
my $c = shift;
$c->res->headers->content_type('text/plain');
$c->res->content->asset(Mojo::Asset::File->new(path => '/etc/passwd'));
$c->rendered(200);
};
app->start;
=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 ($c, $str) = @_;
$c->app->log->debug($str);
});
}
1;
The C<register> method will be called when you load the plugin. And to add your
helper to the application, you can use L<Mojolicious/"helper">.
use Mojolicious::Lite;
plugin 'DebugHelper';
get '/' => sub {
my $c = shift;
$c->debug('It works!');
$c->render(text => 'Hello!');
};
app->start;
A skeleton for a full CPAN compatible plugin distribution can be automatically
generated.
$ mojo generate plugin DebugHelper
And if you have a C<PAUSE> account (which can be requested at
L<http://pause.perl.org>), you are only a few commands away from releasing it
to CPAN.
$ perl Makefile.PL
$ make test
$ make manifest
$ make dist
$ mojo cpanify -u USER -p PASS Mojolicious-Plugin-DebugHelper-0.01.tar.gz
=head2 Bundling assets with plugins
Assets such as templates and static files can be easily bundled with your
plugins, even if you plan to release them to CPAN.
$ mojo generate plugin AlertAssets
$ mkdir Mojolicious-Plugin-AlertAssets/lib/Mojolicious/Plugin/AlertAssets
$ cd Mojolicious-Plugin-AlertAssets/lib/Mojolicious/Plugin/AlertAssets
$ mkdir public
$ echo 'alert("Hello World!");' > public/alertassets.js
$ mkdir templates
$ echo '%= javascript "/alertassets.js"' > templates/alertassets.html.ep
Just 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 C<register> is called.
package Mojolicious::Plugin::AlertAssets;
use Mojo::Base 'Mojolicious::Plugin';
use Mojo::File 'path';
sub register {
my ($self, $app) = @_;
# Append "templates" and "public" directories
my $base = path(__FILE__)->sibling('AlertAssets');
push @{$app->renderer->paths}, $base->child('templates')->to_string;
push @{$app->static->paths}, $base->child('public')->to_string;
}
1;
Both will work just like normal C<templates> and C<public> directories once
you've installed and loaded the plugin, with slightly lower precedence.
use Mojolicious::Lite;
plugin 'AlertAssets';
get '/alert_me';
app->start;
__DATA__
@@ alert_me.html.ep
<!DOCTYPE html>
<html>
<head>
<title>Alert me!</title>
%= include 'alertassets'
</head>
<body>You've been alerted.</body>
</html>
And it works just the same for assets bundled in the C<DATA> section of your
plugin.
package Mojolicious::Plugin::AlertAssets;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
# Append class
push @{$app->renderer->classes}, __PACKAGE__;
push @{$app->static->classes}, __PACKAGE__;
}
1;
__DATA__
@@ alertassets.js
alert("Hello World!");
@@ alertassets.html.ep
%= javascript "/alertassets.js"
=head2 Post-processing dynamic content
While post-processing tasks are generally very easy with the hook
L<Mojolicious/"after_dispatch">, for content generated by the renderer it is a
lot more efficient to use L<Mojolicious/"after_render">.
use Mojolicious::Lite;
use IO::Compress::Gzip 'gzip';
hook after_render => sub {
my ($c, $output, $format) = @_;
# Check if "gzip => 1" has been set in the stash
return unless $c->stash->{gzip};
# Check if user agent accepts gzip compression
return unless ($c->req->headers->accept_encoding // '') =~ /gzip/i;
$c->res->headers->append(Vary => 'Accept-Encoding');
# Compress content with gzip
$c->res->headers->content_encoding('gzip');
gzip $output, \my $compressed;
$$output = $compressed;
};
get '/' => {template => 'hello', title => 'Hello', gzip => 1};
app->start;
__DATA__
@@ hello.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>Compressed content.</body>
</html>
=head2 Streaming
You don't have to render all content at once, the method
L<Mojolicious::Controller/"write"> can also be used to stream a series of
smaller chunks.
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
# Prepare body
my $body = 'Hello World!';
$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, '';
$drain = undef unless length $body;
$c->write($chunk, $drain);
};
$c->$drain;
};
app->start;
The drain callback will be executed whenever the entire previous chunk of data
has actually been written.
HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Content-Length: 12
Server: Mojolicious (Perl)
Hello World!
=head2 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<Mojolicious::Controller/"write_chunk"> come in handy. A common use would be
to send the C<head> section of an HTML document to the browser in advance and
speed up preloading of referenced images and stylesheets.
use Mojolicious::Lite;
get '/' => sub {
my $c = shift;
$c->write_chunk('<html><head><title>Example</title></head>' => sub {
my $c = shift;
$c->finish('<body>Example</body></html>');
});
};
app->start;
The optional drain callback ensures that all previous chunks have been written
before processing continues. To end the stream you can call
L<Mojolicious::Controller/"finish"> or write an empty chunk of data.
HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Transfer-Encoding: chunked
Server: Mojolicious (Perl)
29
<html><head><title>Example</title></head>
1b
<body>Example</body></html>
0
Especially in combination with long inactivity timeouts this can be very useful
for Comet (long polling). Due to limitations in some web servers this might not
work perfectly in all deployment environments.
=head2 Encoding
Templates stored in files are expected to be C<UTF-8> by default, but that can
be easily changed with L<Mojolicious::Renderer/"encoding">.
$app->renderer->encoding('koi8-r');
All templates from the C<DATA> section are bound to the encoding of the Perl
script.
use Mojolicious::Lite;
get '/heart';
app->start;
__DATA__
@@ heart.html.ep
I ♥ Mojolicious!
=head2 Base64 encoded DATA files
Base64 encoded static files such as images can be easily stored in the C<DATA>
section of your application, similar to templates.
use Mojolicious::Lite;
get '/' => {text => 'I ♥ Mojolicious!'};
app->start;
__DATA__
@@ 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 command L<Mojolicious::Command::inflate> will
write all templates and static files from the C<DATA> section into actual files
in the C<templates> and C<public> directories.
$ ./myapp.pl inflate
=head2 Customizing the template syntax
You can easily change the whole template syntax by loading
L<Mojolicious::Plugin::EPRenderer> with a custom configuration.
use Mojolicious::Lite;
plugin EPRenderer => {
name => 'mustache',
template => {
tag_start => '{{',
tag_end => '}}'
}
};
get '/:name' => {name => 'Anonymous'} => 'index';
app->start;
__DATA__
@@ index.html.mustache
Hello {{= $name }}.
L<Mojo::Template> contains the whole list of available options.
=head2 Adding your favorite template system
Maybe you would prefer a different template system than C<ep>, which is provided
by L<Mojolicious::Plugin::EPRenderer>, and there is not already a plugin on CPAN
for your favorite one. All you have to do, is to add a new C<handler> with
L<Mojolicious::Renderer/"add_handler"> when C<register> is called.
package Mojolicious::Plugin::MyRenderer;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
my ($self, $app) = @_;
# Add "mine" handler
$app->renderer->add_handler(mine => sub {
my ($renderer, $c, $output, $options) = @_;
# Check for one-time use inline template
my $inline_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 = 'Hello World!';
# Or just die if an error occurs
die 'Something went wrong with the template';
});
}
1;
An C<inline> template, if provided by the user, will be passed along with the
options. You can use L<Mojolicious::Renderer/"template_path"> to search the
C<templates> directories of the application, and
L<Mojolicious::Renderer/"get_data_template"> to search the C<DATA> sections.
use Mojolicious::Lite;
plugin 'MyRenderer';
# Render an inline template
get '/inline' => {inline => '...', handler => 'mine'};
# Render a template from the DATA section
get '/data' => {template => 'test'};
app->start;
__DATA__
@@ test.html.mine
...
=head2 Adding a handler to generate binary data
By default the renderer assumes that every C<handler> generates characters that
need to be automatically encoded, but this can be easily disabled if you're
generating bytes instead.
use Mojolicious::Lite;
use Storable 'nfreeze';
# 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} = 'storable'
if exists $args->{storable} || exists $c->stash->{storable};
});
get '/' => {storable => {i => '♥ mojolicious'}};
app->start;
The hook L<Mojolicious/"before_render"> can be used to make stash values like
C<storable> special, so that they no longer require a C<handler> value to be set
explicitly.
# Explicit "handler" value
$c->render(storable => {i => '♥ mojolicious'}, handler => 'storable');
# Implicit "handler" value (with "before_render" hook)
$c->render(storable => {i => '♥ mojolicious'});
=head1 MORE
You can continue with L<Mojolicious::Guides> now or take a look at the
L<Mojolicious wiki|http://github.com/kraih/mojo/wiki>, which contains a lot more
documentation and examples by many different authors.
=head1 SUPPORT
If you have any questions the documentation might not yet answer, don't
hesitate to ask on the
L<mailing list|http://groups.google.com/group/mojolicious> or the official IRC
channel C<#mojo> on C<irc.perl.org>
(L<chat now!|https://chat.mibbit.com/?channel=%23mojo&server=irc.perl.org>).
=cut
|