Not a developer? Go to MovableType.com

Documentation

The Template Context

When a template is being published, a “context” is maintained while the page is processed and subsequently published. Template tags can store variables and information in the context to be used by other tags. This is the best way to maintain state during the process of publishing a page.

To store or retrieve a variable, use the “stash” method.

Storing values in the stash

sub handler {
     my ($ctx, $args, $cond) = @_;
     $ctx->stash("some stash key", "some value");
}

Retrieving values from the stash

sub handler {
     my ($ctx, $args, $cond) = @_;
     my $value = $ctx->stash("some stash key");
     # do something
}

How does this relate to our previous example. Let’s take a look:

 1 sub LoopTenTimes {
 2     my ($ctx, $args, $cond) = @_;
 3     my $out = "";
 4     for (my $i = 1; $i <= 10; $i++) {
 5         $ctx->stash("current_loop_number",$i);
 6         defined(my $txt = $ctx->slurp($args,$cond)) or return;
 7         $out .= "$i - $txt";
 8     }
 9     return $out;
10 }

You should notice two things. The first might be a call to the enigmatic slurp() method. The slurp method performs the simple function of returning the results from evaluating the contents or template code contained by the block tag. In the code sample above, this method is used to prepend to the evaluated template code the loop count each time the loop is iterated over.

Secondly, you may notice that within the for loop we are placing an element onto the stash. The name of this item is current_loop_number. Each time through the loop it is updated to store the number of times the loop has been processed up until that point in time.

Once it is stashed, we can reference it later and in another tag.

sub IfOdd {
    my ($ctx, $args, $cond) = @_;
    my $num = $ctx->stash('current_loop_number');
    if ($num % 2 == 0) {
        return 0;
    } else {
        return 1;
    }
}

You will notice that the IfOdd handler then retrieves this element off of the stash and if the number retrieved is an odd number the handler returns true, or 1, else it returns false or 0. In this way, the template context’s stash is a way for developers to maintain the state of the template and template tag(s) being processed.

Throwing Errors from Your Template Tags

At any point in any of your template tag handlers you may encounter a condition under which the best course of action is to terminate the publishing process and return an error. In these situations one can utilize the template context to return an error, complete with an error message that will be displayed to the user. For example:

sub handler {
  my ($ctx, $args, $cond) = @_;
  # do something
  if (<error condition>) {
      return $ctx->error("Something went horribly wrong.");
  }
  return $html;
}
Back

Leave a Comment