Creating Date Template Tags in Movable Type
To bump up the frequency of posts here and as part of my commitment to restart the mt-dev list I moderate, I'm going to do something a little bit different from what I've been posting with a developer's tip.
Movable Type is filled with tons of potential and diamonds in the rough you can use to build some great software with. Here is a small piece of developer knowledge I came across while recently developing Tags.App and have not seen documented anywhere. It's for creating a date template tag in MT 3.2.
MT has several variable tags for inserting dates (timestamps) into templates. This is not surprising since one of the core attributes of weblogs are that they are mostly chronological in order.
Part of MT's smart design is that all of these tags support a format attribute that defines how the date should be displayed using a set of Date Format Specifiers. This is quite powerful because it gives template developers a great deal of flexibility and control in a consistent manner. There is also a lessor known format_name attribute that only recognizes the value rfc_822. (RFC822 is the date format standard that email and web servers use.)
Having your date tags support the shared format attribute that all of MT's date tags share only makes sense for a number of reasons. I've written numerous plugins that introduced date tags of their own. Let's see how you do that in your code.
Creating a date tag is a two step process though your specific situation will likely require more.
The first step is taking the MT timestamp value and adding it to the tag attributes with a key of ts.
The second is passing the value along with the Context object and conditions hash to the _hdlr_date method in MT::Template::ContextHandlers where the magic formatting happens.
Here is a simple example of how this looks:
MT::Template::Context->add_tag(SomeDateTag=>&date_tag);
sub date_tag {
my($ctx,$args) = @_;
$args->{ts} = $ctx->stash('some_mt_timestamp');
require MT::Template::ContextHandlers;
MT::Template::ContextHandlers::_hdlr_date(@_);
}
Making Date Tags Better
While this works I'd like to see that support encouraged and streamlined by the MT API. As a plugin developer this is how I'd like to create a date tag in MT:
MT::Template::Context->add_date_tag(
SomeDateTag=>&date_tag
);
sub date_tag { $_[0]->stash('some_mt_timestamp') }
What happens here is that we declare our tag as a special case of a variable tag using add_date_tag and in out handler method simply return the unformatted MT timestamp value. By declaring the tag as a date to MT's template engine the system automatically passes the returned value through the date formatter before inserting it into a template.
It's a simple change that makes code cleaner and the ability to maintain and enhancement all date tags in the future much easier.
