Mojolic...ndering(3)
π NAME π
Mojolicious::Guides::Rendering(3) β Rendering content. Yeah bestie, it's from the User Contributed Perl Documentation, and it's all about rendering content.
πΈ OVERVIEW πΈ
Okay so this whole document explains content generation with the Mojolicious renderer. That's the vibe. β¨
π¦ CONCEPTS π¦
Essentials every Mojolicious developer should know. No cap, these are the basics you actually need.
π 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 template.format.handler scheme, with template defaulting to controller/action or the route name, format defaulting to html and handler to ep.
{controller => 'users', action => 'list'} -> 'users/list.html.ep'
{template => 'foo', format => 'txt'} -> 'foo.txt.ep'
{template => 'foo', handler => 'epl'} -> 'foo.html.epl'
The controller value gets converted from CamelCase to snake_case using decamelize in Mojo::Util and - characters replaced with /.
{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 templates directories of the application, which can be customized with paths in Mojolicious::Renderer, or one of the the DATA sections from classes in Mojolicious::Renderer.
__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. π
π§ Embedded Perl π§
Mojolicious includes a minimalistic but very powerful template system out of the box called Embedded Perl or ep for short. It is based on Mojo::Template and allows the embedding of Perl code right into actual content using a small set of special tags and line start characters. For all templates strict, warnings, utf8 and Perl 5.16 features 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 <, >, &, ' and " in results from Perl expressions, which is the default to prevent XSS attacks against your application.
<%= 'I β₯ Mojolicious!' %>
<%== '<p>I β₯ Mojolicious!</p>' %>
Only 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 $self and $c.
$c->stash(name => 'tester');
Hello <%= $name %> from <%= $c->tx->remote_address %>.
A prefix like 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'} %>
π BASICS π
Most commonly used features every Mojolicious developer should know about. These are the go-to moves. π
π Automatic rendering π
The renderer can be manually started by calling the method render in Mojolicious::Controller, but that's usually not necessary, because it will get automatically called if nothing has been rendered after the router finished its work. This also means you can have routes pointing only to templates without actual actions.
$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 controller_class in Mojolicious.
You can also disable automatic rendering with the method render_later in Mojolicious::Controller, which can be very useful to delay rendering when a non-blocking operation has to be performed first.
$c->render_later;
π¦ Rendering templates π¦
The renderer will always try to detect the right template, but you can also use the 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 format and 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 render_maybe in Mojolicious::Controller to try multiple alternatives.
$c->render_maybe('localized/baz') or $c->render('foo/bar/baz');
π 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 render_to_string in Mojolicious::Controller.
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.
πΈ Template variants πΈ
To make your application look great on many different devices you can also use the 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.
β¨ Rendering inline templates β¨
Some renderers such as ep allow templates to be passed inline.
$c->render(inline => 'The result is <%= 1 + 1 %>.');
Since auto-detection depends on a path you might have to supply a handler too.
$c->render(inline => "<%= shift->param('foo') %>", handler => 'epl');
π Rendering text π
Characters can be rendered to bytes with the text stash value, the given content will be automatically encoded with encoding in Mojolicious::Renderer.
$c->render(text => 'I β₯ Mojolicious!');
π«Ά Rendering data π«Ά
Bytes can be rendered with the data stash value, no encoding will be performed.
$c->render(data => $bytes);
π Rendering JSON π
The json stash value allows you to pass Perl data structures to the renderer which get directly encoded to JSON with Mojo::JSON.
$c->render(json => {foo => [1, 'test', 3]});
π₯ Status code π₯
Response status codes can be changed with the status stash value.
$c->render(text => 'Oops.', status => 500);
π Content type π
The Content-Type header of the response is actually based on the MIME type mapping of the 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 types in Mojolicious.
# Add new MIME type
$app->types->type(md => 'text/markdown');
π§ Stash data π§
Any of the native Perl data types can be passed to templates as references through the stash in Mojolicious::Controller.
$c->stash(description => 'web framework');
$c->stash(frameworks => ['Catalyst', 'Mojolicious', 'mojo.js']);
$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 stash in Mojolicious::Plugin::DefaultHelpers.
% if (my $spinoffs = stash 'spinoffs') {
Minion is a <%= $spinoffs->{minion} %>.
% }
π 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]);
So we split helpers into two flavors, bestie: the default helpers, which are your general-purpose besties like dumper in Mojolicious::Plugin::DefaultHelpers, and the tag helpers like link_to in Mojolicious::Plugin::TagHelpers β those are the template-specific ones, mostly there to generate HTML tags for you. π
%= link_to Mojolicious => 'https://mojolicious.org'
And in controllers you can also hit the method helpers in Mojolicious::Controller to fully qualify your helper calls, so they never beef with existing methods you already have. No collisions, periodt. β¨
my $serialized = $c->helpers->dumper([1, 2, 3]);
The full guest list of built-in helpers lives in Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers. π
πΈ Static files πΈ
Static files get served automatically from your application's public directories β and you can customize those with paths in Mojolicious::Static, or with one of the DATA sections from classes in Mojolicious::Static. And if that's still not enough (greedy, love that for you), you can serve them manually with reply->static in Mojolicious::Plugin::DefaultHelpers and reply->file in Mojolicious::Plugin::DefaultHelpers. π«Ά
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
$c->reply->static('index.html');
};
get '/some_download' => sub ($c) {
$c->res->headers->content_disposition('attachment; filename=bar.png;');
$c->reply->static('foo/bar.png');
};
get '/leak' => sub ($c) {
$c->reply->file('/etc/passwd');
};
app->start;
β οΈ Okay so see that/leakexample? That is literally serving/etc/passwdto anybody who asks. It's here to show you howreply->fileworks, not because leaking your system files is a vibe. Do not ship that. π
By default static files don't use a prefix β they're just served with higher precedence than routes. You can change that with prefix in Mojolicious::Static. π₯
# Serve static files only with a "/static" prefix
$app->static->prefix('/static');
And to let the prefix be configured dynamically, use url_for_file in Mojolicious::Controller to generate URLs with it. Lots of tag helpers will also pick up the prefix automatically when it makes sense. π
π Static assets π
Okay so ngl, Mojolicious doesn't have any special support for frontend frameworks like Vue.js <https://vuejs.org> and React <https://reactjs.org>. But the public/assets directory is reserved for static assets that bundlers like Webpack <https://webpack.js.org> and Rollup.js <https://rollupjs.org> create ahead of time. π¦
Asset files can be literally any type β they just have to follow the [name].[checksum].[extensions] naming scheme, like myapp.ab1234cd5678ef.js. Then you can use url_for_asset in Mojolicious::Controller or asset_tag in Mojolicious::Plugin::TagHelpers to generate URLs without ever having to know the checksum. Iconic behavior, honestly. β¨
# "/assets/myapp.ab1234cd5678ef.js"
$c->url_for_asset('/myapp.js');
# "<script src="/assets/myapp.ab1234cd5678ef.js"></script>"
$c->asset_tag('/myapp.js');
If your app runs in development mode, all assets get served with a Cache-Control: no-cache header β that speeds up development by stopping the browser from caching stuff. And on top of that, all assets following the [name].development.[extensions] naming scheme, like myapp.development.js, have higher precedence than assets with checksums. So you can just overwrite your assets during development instead of manually deleting them every single time they get rebuilt with a different checksum. The way that saves you π§
# "/assets/foo/bar.development.js"
$c->url_for_asset('/foo/bar.js');
Webpack configuration <https://webpack.js.org/configuration/> example (webpack.config.js):
import Path from '@mojojs/path';
const isDev = process.env.MOJO_MODE === 'development';
export default {
output: {
filename: isDev ? '[name].development.js' : '[name].[chunkhash].js',
path: Path.currentFile().sibling('public', 'assets').toString(),
publicPath: ''
},
// Add your own rules and entry point here
};
Rollup configuration <https://rollupjs.org/guide/en/#configuration-files> example (rollup.config.js):
import Path from '@mojojs/path';
const isDev = process.env.MOJO_MODE === 'development';
export default {
output: {
entryFileNames: isDev ? '[name].development.[ext]' : '[name].[hash].[ext]',
dir: Path.currentFile().sibling('public', 'assets').toString(),
format: 'iife'
},
// Add your own rules and entry point here
};
Everything else is up to your bundler of choice, so go consult its docs for more. And where you keep your asset sources β like your .vue and .jsx files β doesn't matter at all, as long as your bundler can find them. Using a directory named assets or frontend in your application root directory is a good best practice though. π
π Content negotiation π
For resources with different representations that need truly RESTful content negotiation, you can use respond_to in Mojolicious::Plugin::DefaultHelpers instead of render in Mojolicious::Controller. π
# /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 gets selected automatically from the _format GET/POST parameter, the format stash value, or the Accept request header β and it's stored in the format stash value. To change MIME type mappings for the Accept request header or the Content-Type response header, use types in Mojolicious. π
$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 are your go-to for representations too complex to squeeze 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 any fallback gets used, or an empty 204 response is 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 accepts in Mojolicious::Plugin::DefaultHelpers. Main character energy tbh. β
π Rendering exception and not_found pages π
By now you've probably already run into the built-in 404 (Not Found) and 500 (Server Error) pages β they render automatically whenever you make a mistake. Those are fallbacks, for when your own exception handling fails, which is especially helpful during development. And you can render them manually too, with the helpers reply->exception in Mojolicious::Plugin::DefaultHelpers and reply->not_found in Mojolicious::Plugin::DefaultHelpers. π
use Mojolicious::Lite -signatures;
use Scalar::Util qw(looks_like_number);
get '/divide/:dividend/by/:divisor' => sub ($c) {
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 change the templates of those pages, because in production you most likely want to show your users something a little more on-brand. The renderer will always try to find exception.$mode.$format.* or 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 default exception format is html, but you can change that at both application and controller level. Out of the box there are handlers for html, txt and json. There are also various exception helpers in Mojolicious::Plugin::DefaultHelpers for you to overload and change the default behavior. π₯
use Mojolicious::Lite -signatures;
app->exception_format('json');
get '/json' => sub ($c) {
die 'Just a test';
};
get '/txt' => sub ($c) {
$c->exception_format('txt');
die 'Just a test';
};
app->start;
The hook before_render in Mojolicious makes even more advanced customizations possible, by letting you intercept and modify the arguments passed to the renderer. Look at you go. π
use Mojolicious::Lite -signatures;
hook before_render => sub ($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
return unless $c->accepts('json');
$args->{json} = {exception => $c->stash('exception')};
};
get '/' => sub { die "This sho...ALL GLORY TO THE HYPNOTOAD!\n" };
app->start;
π§ Layouts π§
Most of the time when you're using ep templates you'll want to wrap your generated content in an HTML skeleton β and thanks to layouts, that's absolutely trivial. Obsessed. π
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>
okay so the whole vibe is: you pick the right layout template with the layout helper from Mojolicious::Plugin::DefaultHelpers, and then you drop the result of the current template into it with the content helper, also from Mojolicious::Plugin::DefaultHelpers. that's literally it, that's the whole trick π
and yeah, you can absolutely pass normal stash values along to the layout helper too, like:
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>
and if the layout helper is giving you main-character fatigue, you can lowkey skip it and just use the layout stash value instead, or call render in Mojolicious::Controller with the layout argument:
$c->render(template => 'mytemplate', layout => 'mylayout');
want that layout energy everywhere, application-wide, no cap? set a layout stash value with defaults in Mojolicious:
$app->defaults(layout => 'mylayout');
bestie listen, layouts also work with render_to_string in Mojolicious::Controller β BUT π¨ the layout value has to be passed as a render argument, not a stash value. the way that distinction matters fr fr:
my $html = $c->render_to_string('reminder', layout => 'mail');
π§© Partial templates π§©
bigger templates? messy. break them up into smaller, more manageable chunks β so chic β¨ and these partial templates can be shared with other templates too, which is the actual slay here. just use the include helper in Mojolicious::Plugin::DefaultHelpers to smoosh 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 literally whatever you want, but a leading underscore is the commonly used naming convention (iykyk π).
π Reusable template blocks π
repeating yourself is never the moment β that's why you can build reusable template blocks in ep that work very similar to normal Perl functions, using the begin and end keywords. π
β οΈ heads up bestie: both keywords are part of the surrounding tag and not actual Perl code, so there can only be whitespace afterbeginand beforeend. do not test this. she will not forgive you.
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 that template to Perl code could look like this β not me showing you the whole pipeline π:
my $output = '';
my $block = sub ($name) {
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;
and okay, template blocks cannot be shared between templates (sad, I know π), but the most common use is passing parts of a template to helpers, which is genuinely iconic behavior.
π¦ Adding helpers π¦
the rule is: keep your actions small and reuse as much code as possible. helpers make this so easy β they get passed the current controller object as first argument, and like... you can use them to do pretty much anything an action could do. obsessed.
use Mojolicious::Lite -signatures;
helper debug => sub ($c, $str) {
$c->app->log->debug($str);
};
get '/' => sub ($c) {
$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 their last argument β which means you get extremely pleasant-to-use tag helpers and filters, no notes. and wrapping the helper result into a Mojo::ByteStream object can prevent accidental double escaping (the silent killer π):
use Mojolicious::Lite -signatures;
use Mojo::ByteStream;
helper trim_newline => sub ($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 myapp.* to keep helpers from getting exposed in templates as functions β and to organize them into namespaces as your app grows. every prefix automatically becomes a helper that returns a proxy object containing the current controller object, and on that proxy you call the nested helpers. it's giving organizational queen π
use Mojolicious::Lite -signatures;
helper 'cache_control.no_caching' => sub ($c) { $c->res->headers->cache_control('private, max-age=0, no-cache') };
helper 'cache_control.five_minutes' => sub ($c) { $c->res->headers->cache_control('public, max-age=300') };
get '/news' => sub ($c) {
$c->cache_control->no_caching;
$c->render(text => 'Always up to date.');
};
get '/some_older_story' => sub ($c) {
$c->cache_control->five_minutes;
$c->render(text => 'This one can be cached for a bit.');
};
app->start;
and yes, helpers can also be redefined β but do that very carefully to avoid conflicts. like, carefully carefully. π«Ά
πΈ Content blocks πΈ
the content_for helper in Mojolicious::Plugin::DefaultHelpers lets you pass whole blocks of content from one template to another, which is lowkey perfect when your layout has distinct sections β sidebars, bestie, 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>
π Forms π
to build HTML forms more efficiently you can use tag helpers like form_for in Mojolicious::Plugin::TagHelpers β and it can automatically select a request method for you if a route name is provided. fancy. and since most browsers only allow forms to be submitted with GET and POST, but not request methods like PUT or DELETE, those get spoofed with an _method query parameter. sneaky but legal β¨
use Mojolicious::Lite -signatures;
get '/' => 'form';
# PUT /nothing
# POST /nothing?_method=PUT
put '/nothing' => sub ($c) {
# 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 helpers flash in Mojolicious::Plugin::DefaultHelpers and redirect_to in Mojolicious::Plugin::DefaultHelpers are often used together to prevent double form submission β that way the user gets a confirmation message that vanishes if they reload the page they've been redirected to. it's giving responsible UX π
π₯ Form validation π₯
you can use validation in Mojolicious::Plugin::DefaultHelpers to validate GET and POST parameters submitted to your application. important: all unknown fields will be ignored by default, so you have to decide which fields should be required or optional before you can perform checks on their values. and every check is performed right away, so you can use the results immediately to build more advanced validation logic with methods like is_valid in Mojolicious::Validator::Validation. periodt.
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
# Check if parameters have been submitted
my $v = $c->validation;
return $c->render('index') unless $v->has_data;
# Validate parameters ("pass_again" depends on "pass")
$v->required('user')->size(1, 20)->like(qr/^[a-z0-9]+$/);
$v->required('pass_again')->equal_to('pass') if $v->optional('pass')->size(7, 500)->is_valid;
# Check if validation failed
return $c->render('index') if $v->has_error;
# Render confirmation
$c->render('thanks');
};
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 Mojolicious::Plugin::TagHelpers will automatically remember their previous values and add the class field-with-error for fields that failed validation, so styling with CSS is way easier. iconique. look:
<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 "CHECKS" in Mojolicious::Validator. go read it, bestie, there's so many.
β Adding form validation checks β
validation checks can be registered with add_check in Mojolicious::Validator β and here's the twist: they return a false value if they were successful π (yes, backwards from what your brain wants, I know). a true value may be used to pass along additional information, which can then be retrieved with error in Mojolicious::Validator::Validation.
okay so here's the custom range check living its best life inside a full little app β we add the check, the form posts, validation happens, and if it fails the form comes right back ππ
use Mojolicious::Lite -signatures;
# Add "range" check
app->validator->add_check(range => sub ($v, $name, $value, $min, $max) {
return $value < $min || $value > $max;
});
get '/' => 'form';
post '/test' => sub ($c) {
# Validate parameters with custom check
my $v = $c->validation;
$v->required('number')->range(3, 23);
# Render form again if validation failed
return $c->render('form') if $v->has_error;
# Prevent double form submission with redirect
$c->flash(number => $v->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>
π‘οΈ Cross-site request forgery π‘οΈ
CSRF is one of those extremely common web-app attacks where someone tricks your logged-in users into submitting forms they did not intend to send β literally with something as mundane as a link π. The protection is genuinely so easy: all you have to do is add an extra hidden field to your forms with csrf_field in Mojolicious::Plugin::TagHelpers, and validate it with csrf_protect in Mojolicious::Validator::Validation.
use Mojolicious::Lite -signatures;
get '/' => {template => 'target'};
post '/' => sub ($c) {
# Check CSRF token
my $v = $c->validation;
return $c->render(text => 'Bad CSRF token!', status => 403) if $v->csrf_protect->has_error('csrf_token');
my $city = $v->required('city')->param('city');
$c->render(text => "Low orbit ion cannon pointed at $city!") unless $v->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 csrf_token in Mojolicious::Plugin::DefaultHelpers, and then pass it along with the X-CSRF-Token request header. π¦
The token is masked with a fresh random value on every request, so its value changes each time even though it stays bound to the same session. That protects against BREACH attacks, which could otherwise recover a static token from compressed responses. no cap, that's the whole point π₯
π ADVANCED π
Less commonly used and more powerful features β aka the spicy stuff πΆοΈ
𧬠Template inheritance π§¬
Inheritance takes the layout concept above one step further. The helpers content in Mojolicious::Plugin::DefaultHelpers and extends in Mojolicious::Plugin::DefaultHelpers let you build skeleton templates with named blocks that child templates can override. it's giving template family tree π³
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. literally infinite glow-up potential β¨
π Custom responses π
Most response content, static as well as dynamic, gets served through Mojo::Asset::File and Mojo::Asset::Memory objects. For somewhat static content β like cached JSON data or temporary files β you can create your own and use the helper reply->asset in Mojolicious::Plugin::DefaultHelpers to serve them while allowing content negotiation to be performed with Range, If-Modified-Since, and If-None-Match headers. so efficient, so iconic π
use Mojolicious::Lite -signatures;
use Mojo::Asset::File;
get '/leak' => sub ($c) {
$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 rendered in Mojolicious::Controller to tell the renderer when you're done generating a response. main character energy: you're in charge π
use Mojolicious::Lite -signatures;
use Mojo::Asset::File;
get '/leak' => sub ($c) {
$c->res->headers->content_type('text/plain');
$c->res->content->asset(Mojo::Asset::File->new(path => '/etc/passwd'));
$c->rendered(200);
};
app->start;
π§© Helper plugins π§©
Some helpers might be useful enough for you to share them between multiple applications β plugins make that very simple. bestie group project but it actually slaps π«Ά
package Mojolicious::Plugin::DebugHelper;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
sub register ($self, $app, $conf) {
$app->helper(debug => sub ($c, $str) {
$c->app->log->debug($str);
});
}
1;
The register method will be called when you load the plugin. And to add your helper to the application, you can use helper in Mojolicious.
use Mojolicious::Lite -signatures;
plugin 'DebugHelper';
get '/' => sub ($c) {
$c->debug('It works!');
$c->render(text => 'Hello!');
};
app->start;
A skeleton for a full CPAN compatible plugin distribution can be automatically generated. one command and you're cooking π§βπ³
$ 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 releasing it to CPAN. periodt.
$ perl Makefile.PL
$ make test
$ make manifest
$ make dist
$ mojo cpanify -u USER -p PASS Mojolicious-Plugin-DebugHelper-0.01.tar.gz
π 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. cute little starter pack, no cap π
$ 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 register is called. iykyk πΈ
package Mojolicious::Plugin::AlertAssets;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
use Mojo::File qw(curfile);
sub register ($self, $app, $conf) {
# Append "templates" and "public" directories
my $base = curfile->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 templates and public directories once you've installed and loaded the plugin, with slightly lower precedence. lowkey magic, highkey useful β¨
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 DATA section of your plugin. same vibe, different spot π¦
package Mojolicious::Plugin::AlertAssets;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
sub register ($self, $app, $conf) {
# 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"
π Post-processing dynamic content π
While post-processing tasks are generally very easy with the hook after_dispatch in Mojolicious, for content generated by the renderer it is a lot more efficient to use after_render in Mojolicious. efficiency queen behavior π
use Mojolicious::Lite -signatures;
use IO::Compress::Gzip qw(gzip);
hook after_render => sub ($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>
If you want to compress all dynamically generated content you can also activate compress in Mojolicious::Renderer. blanket gzip era π₯
π Streaming π
You don't have to render all content at once β the method write in Mojolicious::Controller can also be used to stream a series of smaller chunks. little sips, not one giant gulp π₯€
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
# Prepare body
my $body = 'Hello World!';
$c->res->headers->content_length(length $body);
# Start writing directly with a drain callback
my $drain = sub ($c) {
my $chunk = substr $body, 0, 1, '';
$c->write($chunk, length $body ? __SUB__ : undef);
};
$c->$drain;
};
app->start;
The drain callback will be executed whenever the entire previous chunk of data has actually been written. so satisfying to watch π
HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Content-Length: 12
Server: Mojolicious (Perl)
Hello World!
Instead of providing a Content-Length header, you can also call finish in Mojolicious::Controller and close the connection manually once youβre done. Manual control moment, slay. π
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
# Prepare body
my $body = 'Hello World!';
# Start writing directly with a drain callback
my $drain = sub ($c) {
my $chunk = substr $body, 0, 1, '';
length $chunk ? $c->write($chunk, __SUB__) : $c->finish;
};
$c->$drain;
};
app->start;
Ngl, this is rather inefficient because it prevents keep-alive, but itβs sometimes necessary for EventSource and similar applications. π«Ά
HTTP/1.1 200 OK
Date: Sat, 13 Sep 2014 16:48:29 GMT
Connection: close
Server: Mojolicious (Perl)
Hello World!
β¨ Chunked transfer encoding β¨
For very dynamic content you might not know the response content length in advance β thatβs exactly where chunked transfer encoding and write_chunk in Mojolicious::Controller come 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. The preload glow-up is real. β¨
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
$c->write_chunk('<html><head><title>Example</title></head>' => sub ($c) {
$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 finish in Mojolicious::Controller or write an empty chunk of data. Easy. π
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. Lowkey important caveat, bestie. π
πΈ Encoding πΈ
Templates stored in files are expected to be UTF-8 by default, but that can be easily changed with encoding in Mojolicious::Renderer.
$app->renderer->encoding('koi8-r');
All templates from the DATA section are bound to the encoding of the Perl script. Cute, right? π§
use Mojolicious::Lite;
get '/heart';
app->start;
__DATA__
@@ heart.html.ep
I β₯ 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. Iconic little storage hack. π
use Mojolicious::Lite;
get '/' => {text => 'I β₯ Mojolicious!'};
app->start;
__DATA__
@@ 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 command Mojolicious::Command::Author::inflate 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 Mojolicious::Plugin::EPRenderer with a custom configuration. Main character template energy. π
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 }}.
Mojo::Template contains the whole list of available options.
π Adding your favorite template system π
Maybe you would prefer a different template system than ep, which is provided by Mojolicious::Plugin::EPRenderer, and there is not already a plugin on CPAN for your favorite one. All you have to do is add a new handler with add_handler in Mojolicious::Renderer when register is called. Build-your-own-renderer era. π οΈ
package Mojolicious::Plugin::MyRenderer;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
sub register ($self, $app, $conf) {
# Add "mine" handler
$app->renderer->add_handler(mine => sub ($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 inline template, if provided by the user, will be passed along with the options. You can use template_path in Mojolicious::Renderer to search the templates directories of the application, and get_data_template in Mojolicious::Renderer to search the DATA sections. Bestie, the renderer is literally handing you the map. πΊοΈ
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
...
π Adding a handler to generate binary data π
By default the renderer assumes that every handler generates characters that need to be automatically encoded, but this can be easily disabled if youβre generating bytes instead. Byte-mode unlocked. π₯
use Mojolicious::Lite -signatures;
use Storable qw(nfreeze);
# Add "storable" handler
app->renderer->add_handler(storable => sub ($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 ($c, $args) {
$args->{handler} = 'storable' if exists $args->{storable} || exists $c->stash->{storable};
});
get '/' => {storable => {i => 'β₯ mojolicious'}};
app->start;
The hook before_render in Mojolicious can be used to make stash values like storable special, so that they no longer require a handler value to be set explicitly. No cap, this is such a neat little shortcut. π
# Explicit "handler" value
$c->render(storable => {i => 'β₯ mojolicious'}, handler => 'storable');
# Implicit "handler" value (with "before_render" hook)
$c->render(storable => {i => 'β₯ mojolicious'});
π MORE π
You can continue with Mojolicious::Guides now, or take a look at the Mojolicious wiki at https://github.com/mojolicious/mojo/wiki, which contains a lot more documentation and examples by many different authors. So much lore. π
π SUPPORT π
If you have any questions the documentation might not yet answer, donβt hesitate to ask in the Forum at https://forum.mojolicious.org, or on IRC at https://web.libera.chat/#mojo. Weβve got you, bestie. π«Ά
And thatβs the whole page, babes! This little rendering saga is from Mojolic...ndering(3), version perl v5.42.0, dated 2026-07-15 β now go make those templates slay. π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Mojolicious 9.480.0-bp160.2.1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms