On 31 Dec 2008, at 15:37, Oliver Charles wrote:

Hi,

This has hit me a few times, and I've just encountered it again, so I
thought it would be good to ask those wiser than I :)

There have been a few times where I could do with querying the
database (which I'd normally do through $c->model), but this is not
available. For example, I've added the option for users to specify how
to display dates on our website, through a variety of formats. I
thought the best way to do this, would be using a Template Toolkit
plugin:

   [% USE user_date %]
   The date is [% user_date.format(some_date) %].

However, this plugin needs to access the user preferences model
($c->model('UserPreference')->date_format($user)). Should I be
instantiating this model (the Catalyst model is a very lightweight
wrapper around a non-catalyst specific model) - or is there a better
option?

- Ollie



The way I do this is by overriding template_vars in my View:TT (which has $c available) to provide format_date and format_datetime subs/ closures (I just let the user specify a TZ, but the idea is the same):

sub template_vars {
    my ($self, $c) = @_;

    return (
        $self->NEXT::template_vars($c),
        format_datetime => sub { $self->format_datetime($c, @_) },
        format_date     => sub { $self->format_date($c, @_) },
    );
};

sub format_datetime {
    my ($self, $c, $date) = @_;
    return unless $date;

    if ($c->user && $c->user->timezone) {
      $date->set_time_zone('UTC');
      $date->set_time_zone($c->user->timezone);
    }

    my $str = $date->strftime("%e %B %Y, %R");
    $str =~ s/^ //;
    return $str;
}


_______________________________________________
List: Catalyst@lists.scsys.co.uk
Listinfo: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/catalyst
Searchable archive: http://www.mail-archive.com/catalyst@lists.scsys.co.uk/
Dev site: http://dev.catalyst.perl.org/

Reply via email to