++ed by:

6 PAUSE users
12 non-PAUSE users.

Jonathan Swartz


Mason::Manual::Tutorial - Mason tutorial


version 2.04


This tutorial provides a tour of Mason by showing how to build a sample Mason/PSGI web application.

Although Mason can be used to generate any kind of content - emails, code, configuration files - it has historically been used most often to generate web pages, hence the focus of this tutorial.

We've chosen to build a micro-blog, which seems to be a popular "hello world" for web frameworks :) - thanks to Dancer and Flask for the inspiration.


A brief discussion on how Mason fits into the MVC (Model-View-Controller) web paradigm.

As a templating system, Mason's chief concern is the View.

In contrast, Mason really has nothing to do with the Model except as a consumer. You can get data into Mason however you like; typical practice is to use an ORM like DBIx::Class or Rose::DB::Object.

The Controller is where things get interesting. Mason provides some Controller facilities, such as parsing web parameters, specifying how URLs are handled, and forwarding control from one handler to another. However, these facilities will not always be as sophisticated as those in a dedicated MVC framework.

Moreover there is a philosophical argument about whether the controller and view should be mixed. Traditional MVC would dictate that they should not be. However, some people (including the author) find it easier to put the controller and view in a single place, at least for simple sites.

So there are two basic ways to use Mason in a web environment:

  1. Use Mason as both the Controller and the View, via the Mason PSGI handler.

  2. Use Mason strictly as the View within a larger MVC framework such as Catalyst, Dancer, or Jifty.

For the purposes of this tutorial, we're going to stick with #1; that will let us demonstrate the widest range of Mason's abilities. Just keep in mind that certain techniques mentioned here are irrelevant if you are in camp #2.


Let's dispense with the model, the part of our app that has little to do with Mason per se. We'll represent blog articles with a single sqlite table:

    create table if not exists articles (
      id integer primary key autoincrement,
      content string not null,
      create_time integer not null,
      title string not null

and a single Rose::DB::Object class to provide an API for it:

    package Blog::Article;
    use Blog::DB;
    use strict;
    use warnings;
    use base qw(Rose::DB::Object);
        table => 'articles',
        auto  => 1,
    sub init_db { Blog::DB->new }


Basically this gives us a Blog::Article object with a constructor for inserting articles, and instance methods for each of the columns. See Rose::DB::Object::Tutorial for more information.


Setup, PSGI plugin

First we install some modules.

    # Requires cpanm: http://search.cpan.org/perldoc?App::cpanminus
    cpanm -S Date::Format DBD::SQLite Mason Mason::Plugin::PSGIHandler Mason::Plugin::HTMLFilters
    cpanm -S Plack Plack::Middleware::Session Rose::DB::Object

mason_psgi_setup, which comes with the PSGI plugin, is the easiest way to set up a Mason psgi app:

    % mason_psgi_setup blog
    writing blog/app.psgi
    writing blog/comps/Base.m
    writing blog/comps/index.m

        cd blog; plackup -r

    to start your server.

We're actually only going to use the app.psgi this time, so let's delete the components it generated:

    % rm blog/comps/*

Now let's take a look at the app.psgi it generated.

     1  #!/usr/bin/perl
     2  use Cwd qw(realpath);
     3  use File::Basename;
     4  use Mason;
     5  use Plack::Builder;
     6  use warnings;
     7  use strict;
     9  # Include Mason plugins here
    10  my @plugins = ('PSGI');
    12  # Create Mason object
    13  my $cwd = dirname( realpath(__FILE__) );
    14  my $interp = Mason->new(
    15      comp_root => "$cwd/comps",
    16      data_dir  => "$cwd/data",
    17      plugins   => \@plugins,
    18  );
    20  # PSGI app
    21  my $app = sub {
    22      my $env = shift;
    23      $interp->handle_psgi($env);
    24  };
    25  builder {
    26      # Include PSGI middleware here
    27      $app;
    28  };

Line 10 lists the Mason plugins we're using. See Mason::Manual::Plugins for information about using and creating plugins.

Line 14-18 creates the Mason interpreter, the central Mason object that creates and controls other Mason objects.

Line 15 specifies the component root, the top of the component hierarchy. All component files must live under this directory, and any component path is considered relative to it.

Line 16 specifies the data directory, a writable directory that Mason uses for various features and optimizations.

Line 20-28 is standard PSGI, creating the PSGI app and adding middleware.

We need to make three small changes to this file. First, to add the HTMLFilters plugin:

     # Include Mason plugins here
 =>  my @plugins = ('PSGI', 'HTMLFilters');

Second, to load our model:

     my $cwd = dirname( realpath(__FILE__) );
 =>  unshift(@INC, "$cwd/lib");
 =>  require Blog::Article;

Third, to add Session support:

     builder {
         # Include PSGI middleware here
 =>      enable 'Session';


Introduction to components

The component - a file with a mix of Perl and HTML - is Mason's basic building block. Pages are usually formed by combining the output from multiple components. An article page for a online magazine, for example, might call separate components for the company masthead, ad banner, left table of contents, and article body.

    |Masthead | Banner Ad        |
    |         |                  |
    |+-------+|Text of Article ..|
    ||       ||                  |
    ||Related||Text of Article ..|
    ||Stories||                  |
    ||       ||Text of Article ..|
    |+-------+|                  |
    |         +------------------+
    |         | Footer           |

The top level component decides the overall page layout. Individual cells are then filled by the output of subordinate components. Pages might be built up from as few as one, to as many as hundreds of components, with each component contributing a chunk of HTML.

Splitting up a page into multiple components gives you roughly the same benefits as splitting up an application into multiple classes: encapsulation, reusability, development concurrency, separation of concerns, etc.

Mason actually compiles components down to Perl/Moose classes, which means that many of the tools you use to develop regular classes - profilers, debuggers, and the like - can be used with Mason components with slight tweaking.

See Mason::Manual::Components for more information about components.


Top-level page components, index files

Here's our first component to serve the home page, /index.m:

     1  <html>
     2    <head>
     3      <link rel="stylesheet" href="/static/css/blog.css">
     4      <title>My Blog: Home</title>
     5    </head>
     6    <body>
     8      <h2>Welcome to my blog.</h2>
    10      <& all_articles.mi &>
    12      <a href="/new_article">Add an article</a>
    14    </body>
    15  </html>

Any component with a .m extension is considered a top-level component, that is, it can be reached by an external URL.

index.m is a special path - it will match the URI of its directory, in this case '/'. (For more special paths and details on how Mason finds page components, see Mason::Manual::RequestDispatch.)

Most of this component contains just HTML, which will be output exactly as written. The single piece of special Mason syntax here is

    10  <& all_articles.mi &>

This is a component call - it invokes another component, whose output is inserted in place.

Splitting a page into multiple components has much the same benefits as splitting a regular program into multiple subroutines or objects: encapsulation, reuse, etc.


Internal components, %-lines, substitution tags, <%init> blocks

Because all_articles.mi has an .mi extension (rather than .m), it is an internal rather than a top-level component, and cannot be reached by an external URL. It can only be reached via a component call from another component.

     1  % if (@articles) {
     2  <b>Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>.</b>
     3  <ul class="articles">
     4  %   foreach my $article (@articles) {
     5    <li><& article/display.mi, article => $article &></li>
     6  %   }
     7  </ul>
     8  % }
     9  % else {
    10  <p>No articles yet.</p>
    11  % }
    13  <%init>
    14  my @articles = @{ Blog::Article::Manager->get_articles
    15      (sort_by => 'create_time DESC') };
    16  </%init>

Three new pieces of syntax here:

Init block

The <%init> block on lines 13-16 specifies a block of Perl code to run when this component is first called. In this case it fetches and sorts the list of articles into a lexical variable @articles.


%-lines - lines beginning with a single '%' - are treated as Perl rather than HTML. They are especially good for loops and conditionals.

Substitution tags

This line

     2  <b>Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>.</b>

shows two substitution tags. Code within <% and %> is treated as a Perl expression, and the result of the expression is output in place.

We see another component call here, article/display.mi, which displays a single article; we pass the article object in a name/value argument pair. Components can be in different directories and component paths can be relative or absolute.


Attributes, dollar-dot notation, passing arguments to components

Next we create /article/display.mi, another internal component:

     1  <%class>
     2  use Date::Format;
     3  my $date_fmt = "%A, %B %d, %Y  %I:%M %p";
     4  </%class>
     6  <%args>
     7  $.article => (required => 1)
     8  </%args>
    10  <div class="article">
    11    <h3><% $.article->title %></h3>
    12    <h4><% time2str($date_fmt, $.article->create_time) %></h4>
    13    <% $.article->content %>
    14  </div>

The <%class> block on lines 1-4 specifies a block of Perl code to place near the top of the generated component class, outside of any methods. This is the place to use modules, declare permanent constants/variables, and define helper methods.

The <%args> block on lines 6-8 declares a single incoming attribute, 'article'. These lines are equivalent to the Moose syntax

    has 'article' => (required => 1);

and in fact, we could have included this line in the <%class> block; <%args> just adds a little sugar and can be nice if you don't already have a <%class> block.

Throughout the component, we refer to the article attribute via the expression


This not-quite-valid-Perl syntax is transformed behind the scenes to


and is one of the rare cases in Mason where we create new syntax on top of Perl, because we want attributes and method calls to be as convenient as possible. The transformation itself is performed by the DollarDot plugin, which is in the default plugins list but can be omitted if the source filtering offends you. :)


Templates / content wrapping, autobases, inheritance, method modifiers

Now we have to handle the URL /new_article, linked from the home page. We do this with our second page component, /new_article.m. It contains only HTML (for now).

     1  <html>
     2    <head>
     3      <link rel="stylesheet" href="/static/css/blog.css">
     4      <title>My Blog: Home</title>
     5    </head>
     6    <body>
     8      <h2>Add an article</h2>
    10      <form action="/article/publish" method=post>
    11        <p>Title: <input type=text size=30 name=title></p>
    12        <p>Text:</p>
    13        <textarea name=content rows=20 cols=70></textarea>
    14        <p><input type=submit value="Publish"></p>
    15      </form>
    17    </body>
    18  </html>

Notice that /index.m and /new_article.m have the same outer HTML template; other pages will as well. It's going to be tedious to repeat this everywhere. And of course, we don't have to. We take the common pieces out of the /index.m and /new_article.m and place them into a new component called /Base.m:

     1  <%augment wrap>
     2    <html>
     3      <head>
     4        <link rel="stylesheet" href="/static/css/mwiki.css">
     5        <title>My Blog</title>
     6      </head>
     7      <body>
     8        <% inner() %>
     9      </body>
    10    </html>
    11  </%augment>

When any page in our hierarchy is rendered, /Base.m will get control first. It will render the upper portion of the template (lines 2-7), then call the specific page component (line 8), then render the lower portion of the template (lines 9-10).

How does this magic work?

  1. Any component named Base.m is an autobase component. It automatically becomes the superclass of any component in its directory and below. Thus, /index.m and /node/view.m both automatically inherit from /Base.m.

  2. When Mason dispatches to a page component like /index.m or /new_article.m, it doesn't call its main method directly. Instead, it calls this chain of methods:

        handle -> render -> wrap -> main

    By default each method in the chain just calls the next one, so the usual behavior is to effectively call main. However, in this case we are augmenting the wrap method, which uses the Moose inner/augment call pattern. In general, any superclass which augments the wrap method can output content before and after its subclasses.

<%augment> is actually a generic block that can be used with any method, though in practice is most often used with wrap. There are analagous blocks for each of Moose's method modifiers: <%before>, <%after>, <%around> and <%override>.

Now, we can remove those nine boilerplate lines from /index.m and /node/view.m.


Form handling, pure-perl components, cmeta

/new_article.m posts to /article/publish. Let's create a component to handle that, called /article/publish.pm. It will not output anything, but will simply take action and redirect.

Note: if you're using an MVC framework, this code will be in a controller rather than a Mason component.

     1  has 'content';
     2  has 'title';
     4  method handle () {
     5      my $session = $m->req->session;
     6      if ( !$.content || !$.title ) {
     7          $session->{message} = "Content and title required.";
     8          $session->{form_data} = $.args;
     9          $m->redirect('/new_article');
    10      }
    11      my $article = Blog::Article->new
    12          ( title => $.title, content => $.content, create_time => time() );
    13      $article->save;
    14      $session->{message} = sprintf( "Article '%s' saved.", $.title );
    15      $m->redirect('/');
    16  }

The .pm extension indicates that this is a pure-perl component. Other than the 'package' and 'use Moose' lines that are generated by Mason, it looks just like a regular Perl class. You could accomplish the same thing with a .m component containing a single <%class> block, but this is easier and more self-documenting.

On lines 1 and 2 we declare incoming attributes. Because this is a top-level page component, the attributes will be populated with our POST parameters.

On line 4 we define a handle method to validate the POST parameters, create the article, and redirect. Recall from the previous chapter that Mason initially calls handle on top-level page components and that it usually defaults to calling render. By defining handle we ensure that the page will not output anything, even in the /Base.m wrapper.

The method keyword comes from Method::Signatures::Simple, which is imported into components by default; see Mason::Component::Moose.

On line 5 we grab the Plack session. $m->req returns the Plack request object; there is an analagous $m->res for the Plack response object.

On lines 7 and 14, we set a message in the Plack session that we want to display on the next page. Rather than just making this work for a specific page, let's add generic code to the template in Base.m:

     7      <body>
 =>  8  % if (my $message = delete($m->req->session->{message})) {
 =>  9        <div class="message"><% $message %></div>
 => 10  % }      
    11        <% inner() %>
    12      </body>

Now, any page can place a message in the session, and it'll appear on just the next page.

On line 8, we place the POST data in the session so that we can repopulate the form with it - we'll do that in the next chapter. $.args is a special component attribute that contains all the arguments passed to the component.



We need to change /new_article.m to repopulate the form with the submitted values when validation fails.

     1  <h2>Add an article</h2>
     3  <% $.FillInForm($form_data) { %>
     4  <form action="/article/publish" method=post>
     5    <p>Title: <input type=text size=30 name=title></p>
     6    <p>Text:</p>
     7    <textarea name=content rows=20 cols=70></textarea>
     8    <p><input type=submit value="Publish"></p>
     9  </form>
    10  </%>
    12  <%init>
    13  my $form_data = delete($m->req->session->{form_data});
    14  </%init>

On lines 3 and 10 we surround the form with a filter. A filter takes a content block as input and returns a new content block which is output in its place. In this case, the FillInForm filter uses HTML::FillInForm to fill in the form from the values in $form_data.

Mason has a few built-in filters, and others are provided in plugins; for example FillInForm is provided in the HTMLFilters plugin.

Another common filter provided by this plugin is HTMLEscape, or H for short. We ought to use this in /article/display.mi when displaying the article title, in case it has any HTML-unfriendly characters in it:

    <h3><% $.article->title |H %></h3>

See Mason::Manual::Filters for more information about using, and creating, filters.


The final set of files for our blog demo are in the eg/blog directory of the Mason distribution, or you can view them at github.


Some topics that we could not fit in here but are worth looking at:

See Mason::Manual for a full list of documentation.




Jonathan Swartz <swartz@pobox.com>


This software is copyright (c) 2011 by Jonathan Swartz.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.