Skip to content


Subversion checkout URL

You can clone with
Download ZIP

Working with the templating system

henryan edited this page · 11 revisions

A word about the templating system (or two)

The first thing to remember, which is really important, is it's all just Perl! You can use Perl in your templates wherever you like! There are several options for the developer to render content. Here is a simple rule: if you need output for the outside of an application stick it in the view. Don't use print to produce html output. The templating system which is being used by Mojolicious is Embedded Perl (EP).

Actually it's just Perl syntax with some special markup. If Perl code is being used inside the template it has to be prefixed with a '%' symbol. If you want to print the value of a variable the tags <%= $variable %> are used.

There is a difference between <%== $variable %> and <%= $variable %> so make sure to read the fine documentation about different templating tags. This will save you plenty of debugging effort and improve your "mojo" using Mojolicious.

Embedded templates

Mojolicious Lite allows you to include templates and image files directly inside your controller file. As a result, it is possible to deliver a complete website as a single application file.

To make embedded templates work, create a __DATA__ section at the bottom of your Mojolicious Lite application file.

The __DATA__ section is then split into separate files using the '@@' tag:

    # /
    get '/' => 'index';

    # /foo
    get '/foo' => 'foo';

    # /bar
    get '/bar' => sub {
        my $self = shift;
        $self->render(text => 'Hi!');
    } => 'bar';


    @@ index.html.ep
    <%= link_to Foo => 'foo' %>.
    <%= link_to Bar => 'bar' %>.

    @@ foo.html.ep
    <a href="<%= url_for 'index' %>">Home</a>.

There are three routes defined in the example above.

Entering the home URL of your website (e.g., would match the first route (i.e., get '/'). Mojolicious automatically assigns the name 'index' to the route.

Since no code reference is associated with the route Mojolicious Lite looks for an embedded template matching the name of the route (i.e., index). So the embedded template "index.html.ep" is finally rendered. If a template gets too large and unwieldy it can easily be moved into a separate file.

For more information please reference the official documentation:

Embedded Perl in Mojolicious

Something went wrong with that request. Please try again.