Not a developer? Go to MovableType.com

Documentation

Transforming the Template’s Source

In the initial phases of rendering a template, Movable Type loads the template’s source code and then invokes the MT::App::CMS::template_source callback to give plugins an opportunity to transform its contents. At this point, developers have the opportunity to modify the template source using any form of string manipulation available to them. The most common technique being the use of a regular expression.

First, let’s look at the input parameters passed to the template_source callback, then we will follow up with sample code.

Input Parameters for MT::App::CMS::template_source

  • $cb - a reference to the current MT::Callback object handling this event.
  • $app - a reference to the MT::App::CMS object processing this request.
  • $src - a reference to the actual template source

Sample Code

Movable Type passes into the callback as input a reference to the actual template source code. This reference allows the developer to make any modifications to the source code that they wish by modifying the variable itself. This also means that you must utilize a relatively obscure syntax in order to “de-reference” the source code being referred to by one of the callback’s input parameters. For example, look at the following code sample and note the double dollar-sign ($$tmpl) associated with the variable holding the template’s source code:

sub my_xfrm_callback {
    my ($cb, $app, $src) = @_;
    my $slug = <<END_TMPL;
A whole bunch of HTML here
END_TMPL
    $$tmpl =~ s/(<li><mt:__trans phrase=\"Utilities\">\n<ul class=\"sub\">)/$1$slug/;
}

Multiple transformations can be performed by a single callback for any given template.

Back

1 Comment

François Nonnenmacher

François Nonnenmacher on December 14, 2009, 6:49 p.m. Reply

There is a typo in the code above, $src should be replaced by $tmpl (or $$tmpl by $$src).