The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Text::MicroMason::Devel - MicroMason Template Syntax And Tips

SYNOPSIS

Mason syntax provides several ways to mix Perl into a text template:

    <%args>
      $name
    </%args>
    % if ( $name eq 'Dave' ) {
      I'm sorry <% $name %>, I'm afraid I can't do that right now.
    % } else {
      <%perl>
        my $hour = (localtime)[2];
        my $daypart = ( $hour > 11 ) ? 'afternoon' : 'morning'; 
      </%perl>
      Good <% $daypart %>, <% $name %>!
    % }

    <& "includes/page_footer.msn" &>

    <%doc>
      Here's a comment describing this greeting message template. 
    </%doc>

DESCRIPTION

This document describes the default template syntax used by Text::MicroMason and how it is turned into runnable Perl code.

TEMPLATE SYNTAX

Text::MicroMason::Base supports a syntax that is mostly a subset of that used by HTML::Mason.

Template Markup

  • literal_text

    Anything not specifically parsed by one of the below rules is interpreted as literal text.

    This is equivalent to a <%text>...</%text> block.

  • <% perl_expr %>

    A Perl expression to be interpolated into the result.

    For example, the following template text will return a scheduled greeting:

        Good <% (localtime)[2]>11 ? 'afternoon' : 'morning' %>.

    The block may span multiple lines and is scoped inside a "do" block, so it may contain multiple Perl statements and it need not end with a semicolon.

        Good <% my $h = (localtime)[2]; $h > 11 ? 'afternoon' 
                                                : 'morning'  %>.

    This is equivalent to an <%output>...</%output> block.

  • % perl_code

    Lines which begin with the % character, without any leading whitespace, may contain arbitrary Perl code to be executed when encountering this portion of the template. Their result is not interpolated into the result.

    For example, the following template text will return a scheduled greeting:

        % my $daypart = (localtime)[2]>11 ? 'afternoon' : 'morning';
        Good <% $daypart %>.

    The line may contain one or more statements. This code is automatically terminated by a semicolon but it is not placed in its own block scope, so it can still open a spanning block scope closed by a later perl block.

    For example, the following template text will return one of two different messages each time it's interpreted:

        % if ( int rand 2 ) {
          Hello World!
        % } else {
          Goodbye Cruel World!
        % }

    This also allows you to quickly comment out sections of a template by prefacing each line with % #.

    This is equivalent to a <%perl>...</%perl> block.

  • <& template_filename, arguments &>

    Includes the results of a separate file containing MicroMason code, compiling it and executing it with any arguments passed after the filename.

    For example, we could place the following template text into an separate file:

        Good <% $ARGS{hour} >11 ? 'afternoon' : 'morning' %>.

    Assuming this file was named "greeting.msn", its results could be embedded within the output of another script as follows:

      <& "greeting.msn", hour => (localtime)[2] &>

    This is equivalent to an <%include>...</%include> block.

  • <%name> ... </%name>

    A named block performs one of the behaviors described in "Named Blocks". The block name at the start and end must match, and must one of the supported block names.

Named Blocks

The following types of named blocks are supported:

  • <%perl> perl_code </%perl>

    Blocks surrounded by %perl tags may contain arbitrary Perl code. Their result is not interpolated into the result.

    These blocks may span multiple lines in your template file. For example, the below template initializes a Perl variable inside a %perl block, and then interpolates the result into a message.

        <%perl> 
          my $count = join '', map "$_... ", ( 1 .. 9 ); 
        </%perl>
        Here are some numbers: <% $count %>

    The code may contain one or more statements. This code is automatically terminated by a semicolon but it is not placed in its own block scope, so it can still open a spanning block scope closed by a later perl block.

    For example, when the below template text is evaluated it will return a sequence of digits:

        Here are some numbers: 
        <%perl> 
          foreach my $digit ( 1 .. 9 ) { 
        </%perl>
            <% $digit %>... 
        <%perl> 
          } 
        </%perl>

    If the block is immediately followed by a line break, that break is discarded. These blocks are not whitespace sensitive, so the template could be combined into a single line if desired.

  • <%init> perl_code </%init>

    Similar to a %perl block, except that the code is moved up to the start of the subroutine. This allows a template's initialization code to be moved to the end of the file rather than requiring it to be at the top.

    For example, the following template text will return a scheduled greeting:

        Good <% $daypart %>.
        <%init> 
          my $daypart = (localtime)[2]>11 ? 'afternoon' : 'morning';
        </%init>
  • <%cleanup> perl_code </%cleanup>

    Similar to a %perl block, except that the code is moved down to the end of the subroutine.

  • <%once> perl_code </%once>

    Similar to a %perl block, except that the code is executed once, when the template is first compiled. (If a caller is using execute, this code will be run repeatedly, but if they call compile and then invoke the resulting subroutine multiple times, the %once code will only execute during the compilation step.)

    This code does not have access to %ARGS and can not generate output. It can be used to define constants, create persistent variables, or otherwise prepare the environment.

    For example, the following template text will return a increasing number each time it is called:

        <%once> 
          my $counter = 1000;
        </%once>
        The count is <% ++ $counter %>.
  • <%args> variable => default </%args>

    Defines a collection of variables to be initialized from named arguments passed to the subroutine. Arguments are separated by one or more newlines, and may optionally be followed by a default value. If no default value is provided, the argument is required and the subroutine will croak if it is not provided.

    For example, adding the following block to a template will initialize the three named variables, and will fail if no a => '...' argument pair is passed:

      <%args>
        $a
        @b => qw( foo bar baz )
        %c => ()
      </%args>

    All the arguments are available as lexically scoped ("my") variables in the rest of the component. Default expressions are evaluated in top-to-bottom order, and one expression may reference an earlier one.

    Only valid Perl variable names may be used in <%args> sections. Parameters with non-valid variable names cannot be pre-declared and must be fetched manually out of the %ARGS hash.

  • <%include> template_filename, arguments </%include>

    Includes the results of a separate file containing MicroMason code, compiling it and executing it with any arguments passed after the filename.

      <%include> "greeting.msn", hour => (localtime)[2] </%include>
  • <%output> ... </%output>

    Produces literal text in the template output. Can be used to surround text that contains other markup tags that should not be interpreted.

  • <%doc> ... </%doc>

    Provides space for template developer documentation or comments which are not included in the output.

TEMPLATE DEVELOPER NOTES

Assembling Perl Source Code

When Text::MicroMason::Base assembles your lexed template into the equivalent Perl subroutine, all of the literal (non-Perl) pieces are converted to $_out->('text'); statements, and the interpolated expressions are converted to $_out->( do { expr } ); statements. Code from %perl blocks and % lines are included exactly as-is.

Your code is eval'd in the Text::MicroMason::Commands package. The use strict; pragma is enabled by default to simplify debugging.

Internal Sub-templates

You can create sub-templates within your template text by defining them as anonymous subroutines and then calling them repeatedly. For example, the following template will concatenate the results of the draw_item sub-template for each of three items:

    <h1>We've Got Items!</h1>
    
    % my $draw_item = sub {
      <p><b><% $_[0] %></b>:<br>
        <a href="/more?item=<% $_[0] %>">See more about <% $_[0] %>.</p>
    % };
    
    <%perl>
      foreach my $item ( qw( Foo Bar Baz ) ) {
        $draw_item->( $item );
      }
    </%perl>

Returning Text from Perl Blocks

To append to the result from within Perl code, call $_out->(text). (The $_out->() syntax is unavailable in older versions of Perl; use the equivalent &$_out() syntax instead.)

For example, the below template text will return '123456789' when it is evaluated:

    <%perl>
      foreach my $digit ( 1 .. 9 ) {
        $_out->( $digit )
      }
    </%perl>

You can also directly manipulate the value $OUT, which contains the accumulating result.

For example, the below template text will return an altered version of its message if a true value for 'minor' is passed as an argument when the template is executed:

    This is a funny joke.
    % $OUT =~ tr[a-z][n-za-m] if $ARGS{minor};

SYNTAX MIXINS

This behavior can be supplemented or overridden by subclasses and mixins. (Of particular interest are the private lex(), assemble(), and eval_sub() methods.) For more information about how these mixin behaviors are implemented and selected, see "Object-Oriented Interface" in Text::MicroMason.

Filters

HTML::Mason provides an expression filtering mechanism which is typically used for applying HTML and URL escaping functions to output.

The Filters mixin provides this capability for Text::MicroMason templates. To select it, add its name to your Mason initialization call:

  my $mason = Text::MicroMason->new( -Filters );

Output expressions may then be followed by "|h" or "|u" escapes; for example this line would convert any ampersands in the output to the equivalent HTML entity:

  Welcome to <% $company_name |h %>

For more information see Text::MicroMason::Filters

ServerPages

The ServerPages mixin replaces the supported template syntax with one similar to that used by the ASP and JSP templating systems.

For more information see Text::MicroMason::ServerPages

SEE ALSO

For the core functionality of this package see Text::MicroMason and Text::MicroMason::Base.

For distribution, installation, support, copyright and license information, see Text::MicroMason::ReadMe.