1 #============================================================= -*-Perl-*-
3 # Template::Plugin::Assert
6 # Template Toolkit plugin module which allows you to assert that
7 # items fetchs from the stash are defined.
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::Assert;
21 use base 'Template::Plugin';
24 use Template::Exception;
27 our $MONAD = 'Template::Monad::Assert';
28 our $EXCEPTION = 'Template::Exception';
34 my $stash = $context->stash;
36 $MONAD->new($stash, shift);
39 # define .assert vmethods for hash and list objects
40 $context->define_vmethod( hash => assert => $vmethod );
41 $context->define_vmethod( list => assert => $vmethod );
47 my ($class, $context, @args) = @_;
48 # create an assert plugin object which will handle simple variable
50 return bless { _CONTEXT => $context }, $class;
54 my ($self, @args) = @_;
57 return if $item eq 'DESTROY';
59 # lookup the named values
60 my $stash = $self->{ _CONTEXT }->stash;
61 my $value = $stash->dotop($stash, $item, \@args);
63 if (! defined $value) {
64 die $EXCEPTION->new( assert => "undefined value for $item" );
70 package Template::Monad::Assert;
72 our $EXCEPTION = 'Template::Exception';
76 my ($class, $stash, $this) = @_;
77 bless [$stash, $this], $class;
81 my ($self, @args) = @_;
82 my ($stash, $this) = @$self;
85 return if $item eq 'DESTROY';
87 my $value = $stash->dotop($stash, $item, \@args);
89 if (! defined $value) {
90 die $EXCEPTION->new( assert => "undefined value for $item" );
101 Template::Plugin::Assert - trap undefined values
107 # throws error if any undefined values are returned
108 [% object.assert.method %]
109 [% hash.assert.key %]
110 [% list.assert.item %]
114 This plugin defines the C<assert> virtual method that can be used
115 to automatically throw errors when undefined values are used.
117 For example, consider this dotop:
121 If C<user.name> is an undefined value then TT will silently ignore the
122 fact and print nothing. If you C<USE> the C<assert> plugin then you
123 can add the C<assert> vmethod between the C<user> and C<name> elements,
126 [% user.assert.name %]
128 Now, if C<user.name> is an undefined value, an exception will be thrown:
130 assert error - undefined value for name
134 Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
138 Copyright (C) 2008 Andy Wardley. All Rights Reserved.
140 This module is free software; you can redistribute it and/or
141 modify it under the same terms as Perl itself.
151 # perl-indent-level: 4
152 # indent-tabs-mode: nil
155 # vim: expandtab shiftwidth=4: