1 #============================================================= -*-Perl-*-
3 # Template::Plugin::Scalar
6 # Template Toolkit plugin module which allows you to call object methods
10 # Andy Wardley <abw@wardley.org>
13 # Copyright (C) 2008 Andy Wardley. All Rights Reserved.
15 # This module is free software; you can redistribute it and/or
16 # modify it under the same terms as Perl itself.
18 #============================================================================
20 package Template::Plugin::Scalar;
21 use base 'Template::Plugin';
24 use Template::Exception;
25 use Scalar::Util qw();
28 our $MONAD = 'Template::Monad::Scalar';
29 our $EXCEPTION = 'Template::Exception';
36 # define .scalar vmethods for hash and list objects
37 $context->define_vmethod( hash => scalar => \&scalar_monad );
38 $context->define_vmethod( list => scalar => \&scalar_monad );
44 # create a .scalar monad which wraps the hash- or list-based object
45 # and delegates any method calls back to it, calling them in scalar
46 # context, e.g. foo.scalar.bar becomes $MONAD->new($foo)->bar and
47 # the monad calls $foo->bar in scalar context
52 my ($class, $context, @args) = @_;
53 # create a scalar plugin object which will lookup a variable subroutine
54 # and call it. e.g. scalar.foo results in a call to foo() in scalar context
65 return if $item eq 'DESTROY';
67 # lookup the named values
68 my $stash = $self->{ _CONTEXT }->stash;
69 my $value = $stash->{ $item };
71 if (! defined $value) {
72 die $EXCEPTION->new( scalar => "undefined value for scalar call: $item" );
74 elsif (ref $value eq 'CODE') {
75 $value = $value->(@_);
81 package Template::Monad::Scalar;
83 our $EXCEPTION = 'Template::Exception';
87 my ($class, $this) = @_;
96 return if $item eq 'DESTROY';
99 if (Scalar::Util::blessed($this)) {
100 # lookup the method...
101 $method = $this->can($item);
104 die $EXCEPTION->new( scalar => "invalid object method: $item" );
107 # ...and call it in scalar context
108 my $result = $method->($this, @_);
119 Template::Plugin::Scalar - call object methods in scalar context
125 # TT2 calls object methods in array context by default
128 # force it to use scalar context
129 [% object.scalar.method %]
131 # also works with subroutine references
132 [% scalar.my_sub_ref %]
136 The Template Toolkit calls user-defined subroutines and object methods
137 using Perl's array context by default. This plugin module provides a way
138 for you to call subroutines and methods in scalar context.
142 Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
146 Copyright (C) 2008 Andy Wardley. All Rights Reserved.
148 This module is free software; you can redistribute it and/or
149 modify it under the same terms as Perl itself.
159 # perl-indent-level: 4
160 # indent-tabs-mode: nil
163 # vim: expandtab shiftwidth=4: