Skip to content

Working with the templating system

MadDud edited this page Feb 1, 2012 · 7 revisions

A word about the templating system (or two)

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

Actually it's just Perl syntax with some special things to take care about. If Perl code is being used inside the template it has to been prefixed with a '%' sign. If you want to print the value of a variable the signs <%= $variable %> are being used. There is a difference between <%== $variable %> and <% $variable %>. Make sure to read the documentation about different templating tags, this will save you plenty of debugging efforts.

Embedded templates

Mojolicious Lite allows you to include templates and image files directly in the controller file.

As a result, it is possible to deliver a complete website as a single file.

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

The __DATA__ section is then split into seperate files using the '@@' characters:

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

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

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

__DATA__

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

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

There are 3 routes defined in the example above.

Entering the home URL of your website (e.g. http://mojolicious.org/) would than match the first route (get '/'). This route gets the name 'index'.

As there is no code reference following the route that could be executed, Mojolicious lite is than looking for an embedded template matching the name of the route (index). So the embedded template "index.html.ep" is finally rendered. In case the template gets too big, it can easily put into a "real" file.

For further documentation, go to:

Embedded Images in Mojolicious Lite

Clone this wiki locally